Swift how to make a square

Swift: Build a Square - Learn how to create a custom shape with this step-by-step tutorial, complete with example code.

Creating a Square with JavaScript

A square can be created in JavaScript using the rect() method of the canvas element. The rect() method takes four parameters: the x and y coordinates of the top left corner of the rectangle, and the width and height of the rectangle. The x and y coordinates represent the position of the rectangle, while the width and height control the dimensions.

For example, the following code creates a square with sides of length 50, located at the coordinates (100,100):


ctx.rect(100,100,50,50);

The rectangle is not visible until you call the fill() or stroke() methods. The fill() method fills the rectangle with the current fill color, while the stroke() method draws the outline of the rectangle with the current line style. For example, the following code draws a blue square with black outlines:


ctx.rect(100,100,50,50);
ctx.fillStyle = "blue";
ctx.fill();
ctx.strokeStyle = "black";
ctx.stroke();

You can also modify the square with other methods. For example, the rotate() method rotates the canvas around the origin, while the scale() method scales the canvas. For example, the following code draws a rotated and scaled square:


ctx.rect(100,100,50,50);
ctx.rotate(Math.PI/4);
ctx.scale(2,2);
ctx.fillStyle = "blue";
ctx.fill();
ctx.strokeStyle = "black";
ctx.stroke();

Creating a square in JavaScript is a simple task. All you need to do is use the rect() method with the appropriate parameters, and then call the fill() or stroke() method to make it visible. You can also use other methods to modify the square, such as the rotate() and scale() methods.

Answers (0)