HTML Canvas Tag

HTML Canvas Tag

A basic guide to the Canvas Tag: Drawing Lines, Rectangles, Circles, Text, Gradients, and Images

·

6 min read

What is the Canvas Tag?

The HTML Canvas element is a bitmap-based drawing surface that is used to draw graphics on a web page.

Note: By default, a canvas has no border and no content.

The <canvas> element is mainly a container for graphics. It allows drawing functions that can be used to create lines, curves, shapes, images, and text. With the Canvas tag, you can create and manipulate graphics using the power of JavaScript.

Syntax:

<canvas id = "script"> Contents... </canvas>

Note: Canvas Tags require both opening and closing tags.

The HTML canvas is a two-dimensional grid of pixels. Each pixel in the grid can be specified with a pair of X/Y coordinates.

For example, let's say our canvas size(width and height) is 250 x 150 pixels. The upper left corner of our canvas will have the coordinates (0, 0), and the bottom right corner will have the coordinates (250, 150).

Attributes: The width and height attribute is necessary to define the size of the canvas. If not specifiied, the defult values of width and height will be 300 pixels and 150 pixels respectively.

🖌️Let's Draw a Line

Let's start by creating a simple straight line:

Step 1: Create the Canvas Element

To create a Canvas element, simply add the <canvas> tag to your HTML document and add the id attribute. We'll also include the width and height attributes to set the size of our canvas area.

<canvas id="myCanvas" width="250" height="150"></canvas>

Step 2: Reference the Canvas Element

Next, find the <canvas> element.

The id attribute, which is a unique identifier, can be referenced in JavaScript by using the HTML DOM method getElementById():

const canvas = document.getElementById("myCanvas");

Step 3: Create a Drawing Object

Now, you need a drawing object for the canvas.

We will create a 2D drawing context using the getContext() method. The getContext() is a built-in HTML object, with properties and methods for drawing:

const ctx = canvas.getContext("2d");

Step 4: Draw on the Canvas

Finally, let's draw on the canvas.

To draw a straight line with the coordinates on a canvas, we can use the following methods:

  • moveTo(x, y) - Starting point of the line.

  • lineTo(x, y) - Ending point of the line.

Use the stroke() method to actually draw a line from the starting point to the ending point:

ctx.moveTo(0,0);
ctx.lineTo(250,150);
ctx.stroke();

The browser will display the text "Your browser does not support the canvas element." as a fallback if it does not support the canvas element.

This is the final code:

<canvas id="myCanvas" width="250" height="150">
Your browser does not support the canvas element.
</canvas>

<script>
const c = document.getElementById("myCanvas");
const ctx = c.getContext("2d");
ctx.moveTo(0, 0);
ctx.lineTo(250, 150);
ctx.stroke();
</script>

Output:

🖌️Canvas tag for a Rectangle

To draw a rectangle on a canvas, we can use the rect() method. This method takes four parameters: The X coordinate of the upper left corner, the Y coordinate of the upper left corner, the width of the rectangle in pixels, and the height of the rectangle in pixels.

ctx.rect(0, 0, 200, 100);

We’ll use the stroke() function to draw the rectangle:

Now, let's use the fillStyle property which sets the background color of the canvas. It can be a CSS color, a gradient, or a pattern.

Note: The default color for fillStyle in HTML canvas is black.

Let's set the fill style of the drawing object to the color blue:

ctx.fillStyle = "#0000FF";

We can also draw a filled-in rectangle with the fillRect() method, which accepts the same parameters as rect(). This method creates a filled-in rectangle and we don't have to use the stroke() or fill() method:

🖌️Canvas tag for a Circle

To draw a circle on a canvas, we can use the following methods:

  • beginPath() - begins a path.

  • arc(x, y, r, startangle, endangle) - creates an arc/curve on the canvas.

    The x and y parameters define the x and y coordinates of the center of the arc/circle. The r parameter defines the radius of the circle. To create a circle, set the startangle to 0 and the endangle to 2*Math.PI.

<script>
const c = document.getElementById("myCanvas");
const ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(125, 75, 60, 0, 2* Math.PI);
ctx.stroke();
</script>

Finally, we call the stroke method to stroke the path and draw a full circle on the canvas:

🖌️Canvas tag for a Text

To draw text on a canvas, we'll be using the font property which defines the font properties for the text and the fillStyle property to add color to the text.

There are two different ways to draw text:

  • fillText(text, x, y) - draws filled text on the canvas. The text is where you want to display the text. The x and y are the coordinates:
<script>
const c = document.getElementById("myCanvas");
const ctx = c.getContext("2d");
ctx.font = "30px Monospace";
ctx.fillStyle = "blue";
ctx.fillText("Canvas Text", 35, 80);
</script>

  • strokeText(text, x, y) - draws text on the canvas (no fill):
<script>
const c = document.getElementById("myCanvas");
const ctx = c.getContext("2d");
ctx.font = "30px Monospace";
ctx.strokeStyle = "blue";
ctx.strokeText("Canvas Text", 35, 80);
</script>

🖌️Canvas tag for a Gradient

To use the gradient, set the fillStyle or strokeStyle property to the gradient, then draw the shape (rectangle, text, or a line).

The addColorStop() method specifies the color stops, and its position along the gradient. Gradient positions can be anywhere between 0 to 1.

There are two different types of gradients:

  • createLinearGradient(x, y, x1, y1) - creates a linear gradient. Here, x and y are the starting points of the gradient and x1 and y1 are the ending points:
<script>
const c = document.getElementById("myCanvas");
const ctx = c.getContext("2d");

// Create gradient
const grd = ctx.createLinearGradient(0, 0, 200, 0);
grd.addColorStop(0, "blue");
grd.addColorStop(1, "yellow");

// Fill with gradient
ctx.fillStyle = grd;
ctx.fillRect(10, 10, 230, 130);
</script>

  • createRadialGradient(x, y, r, x1, y1, r1) - creates a radial/circular gradient. Here, r is the radius of the inner circle of the gradient and r1 is the radius of the outer circle:
<script>
const c = document.getElementById("myCanvas");
const ctx = c.getContext("2d");

// Create gradient
const grd = ctx.createRadialGradient(125, 125, 10, 125, 125, 100);
grd.addColorStop(0, "blue");
grd.addColorStop(1, "yellow");

// Fill with gradient
ctx.fillStyle = grd;
ctx.fillRect(25, 25, 200, 200);
</script>

🖌️Canvas tag for an Image

To draw an image on a canvas, we can use the following method:

  • drawImage(img, x, y) : This method is used to draw the image onto the canvas.
<p><button onclick="myCanvas()">Click Me!</button></p>

<script>
function myCanvas() {
  const c = document.getElementById("myCanvas");
  const ctx = c.getContext("2d");
  const img = document.getElementById("starry");
  ctx.drawImage(img,10,10);
}
</script>

When you click the button, the myCanvas() function is executed, and the image is drawn onto the canvas at the specified position. Try it:

🖌️Canvas tag for a Star(Bonus)

With paths, you can create virtually any kind of 2D shape you want.

Let's draw a polygon shape with 9 points to resemble a star.

To Summarize

The Canvas tag in HTML is a powerful tool for creating dynamic visualizations on the web. It's very useful for creating interactive animations, graphs, charts, and games. By using the power of JavaScript, you can manipulate the Canvas element and create a rich and engaging browsing experience.

However, due to the fact that the canvas tag involves 2D objects and bitmap images, it is essentially a low-level tag that generates raster graphics, which are not scalable and may lose quality when resized, resulting in pixelation or blurriness.

A good alternative to the Canvas tag in HTML is the SVG tag, which we'll discuss later.


References


Thank's for taking the time to read this blog. Hope you found it informative and enjoyable!

Let me know your thoughts. Connect with me on Twitter.

Catch you guys on the next one. Cheers .. ✌️

Did you find this article valuable?

Support Raj Sarkar by becoming a sponsor. Any amount is appreciated!