Drawing shapes is the cornerstone of Canvas programming, opening a gateway to creating stunning graphics and interactive visualizations on the web. In this chapter, we will delve into the basics of drawing shapes in Canvas using JavaScript, exploring various shapes and techniques.
Drawing Shapes
1 Drawing Rectangles
Rectangles are one of the simplest shapes to draw on Canvas. Using the fillRect()
and strokeRect()
methods of the drawing context, we can easily create filled or stroked rectangles, respectively. These methods require parameters specifying the position (x, y) and dimensions (width, height) of the rectangle.
// Drawing a filled rectangle
context.fillRect(x, y, width, height);
// Drawing a stroked rectangle
context.strokeRect(x, y, width, height);
Drawing a Rectangle on Canvas Includes several steps:
- Accessing Canvas Context: First, we need to access the 2D drawing context of the Canvas element. We use the
getContext()
method to obtain the drawing context. - Begin Path: We start a new path by calling
beginPath()
This step is essential as it clears any existing path and prepares the context for drawing a new shape. - Define Rectangle: We use the
rect()
method to define the rectangle's parameters - its starting point (x
,y
) and its width and height (width
,height
). - Styling: Optionally, we can set the stroke and fill styles to define the appearance of the rectangle. This includes setting colors, gradients, or pattern using
strokeStyle
andfillStyle
properties. - Stroke or Fill: Finally, we use either
stroke()
to draw the outline of the rectangle orfill()
to fill the interior of the rectangle with color or pattern.
Example:
// Step 1: Access Canvas Context
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// Step 2: Begin Path
ctx.beginPath();
// Step 3: Define Rectangle
const x = 50;
const y = 50;
const width = 200;
const height = 100;
ctx.rect(x, y, width, height);
// Step 4: Styling (Optional)
ctx.strokeStyle = 'blue'; // Outline color
ctx.lineWidth = 2; // Outline width
ctx.fillStyle = 'lightblue'; // Fill color
// Step 5: Stroke or Fill
ctx.stroke(); // Draw the outline of the rectangle
// Alternatively, use ctx.fill() to fill the rectangle with color
2 Drawing Circles
While Canvas does not have a built-in method to draw circles directly, we can leverage the arc()
method to create circles or arcs. The arc()
method requires parameters for the center coordinates (x, y), radius, start angle, end angle, and optional direction (clockwise or counterclockwise).
// Drawing a circle
context.beginPath();
context.arc(x, y, radius, 0, Math.PI * 2);
context.closePath();
context.fill(blue); // or context.stroke() for stroked circle
Drawing Circle on Canvas includes following steps:
Step 1: Accessing Canvas Context
First, we need to access the Canvas drawing context, which provides method and properties for drawing on the Canvas. We do this by obtaining the Canvas element from the DOM and then accessing its 2D drawing context.
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
Step 2: Defining Circle Parameters
To draw a circle, we need to define its center coordinates (x
, y
) and its radius. Optionally, we can also specify the start and end angles to draw a portion of a circle (arc).
const x = 100; // X-coordinate of the center
const y = 100; // Y-coordinate of the center
const radius = 50; // Radius of the circle
const startAngle = 0; // Starting angle (in radians)
const endAngle = 2 * Math.PI; // Ending angle (in radians), represents a full circle
Step 3: Drawing the Circle
Once we have defined the parameters, we use the arc()
method to draw the circle on the Canvas. The arc()
method takes several arguments:
x
: The x-coordinate of the center of the circle.y
: The y-coordinate of the center of the circle.radius
: The radius of the circle.startAngle
: The starting angle of the arc, in radians.endAngle
: The ending angle of the arc, in radians.anticlockwise
: An optional parameter indicating whether the arc should be drawn in the anticlockwise direction (default isfalse
).
ctx.beginPath(); // Begin a new path
ctx.arc(x, y, radius, startAngle, endAngle); // Define the arc
ctx.closePath(); // Close the path (optional, for better performance)
ctx.stroke(); // Stroke the circle outline
// Alternatively, use ctx.fill() to fill the circle with color
Step 4: Styling Circles
You can customize the stroke style of the circle, including the color, line width, and line cap style, using the appropriate properties of the CanvasRenderingContext2D object.
ctx.strokeStyle = 'blue'; // Set stroke color
ctx.lineWidth = 2; // Set line width
ctx.lineCap = 'round'; // Set line cap style (round, butt, square)
Similarly, you can customize the fill style of the circle, including the color and gradient, using the fillStyle
property.
ctx.fillStyle = 'green'; // Set fill color
3 Drawing Lines
Lines can be drawn on Canvas using the moveTo()
and lineTo()
methods of the drawing context. The moveTo()
method sets the starting point of the line, while lineTo()
adds a line segment from the current point to the specified point. After defining the path, we can stroke it using the stroke()
method.
// Drawing a line
context.beginPath();
context.moveTo(x1, y1); // Starting point
context.lineTo(x2, y2); // Ending point
context.stroke();
4 Drawing Polygons
Polygons, including triangles, quadrilaterals, and irregular shapes, can be drawn by defining a path using the moveTo()
and lineTo()
methods. By connecting multiple points with lines, we can create intricate shapes. Once the path is defined, we can fill or stroke it using appropriate methods.
// Drawing a triangle
context.beginPath();
context.moveTo(x1, y1);
context.lineTo(x2, y2);
context.lineTo(x3, y3);
context.closePath();
context.fill(); // or context.stroke() for stroked triangle
Styling Shapes
1 Stroke Style
The stroke style defines the color, gradient, or pattern used for the outline of shapes. We can set the stroke style using the strokeStyle
property:
ctx.strokeStyle = 'blue'; // Set stroke color to blue
ctx.lineWidth = 2; // Set line width
2 Fill Style
The fill style defines the color, gradient, or pattern used to fill the interior of shapes. We can set the fill style using the fillStyle
property:
ctx.fillStyle = 'green'; // Set fill color to green