W3docs

Canvas Drawing

On this page, you can find useful information about the HTML <canvas> element, as well as to learn to draw with canvas step by step with our code examples.

JavaScript is used to draw on the canvas. We will do this step by step.

1. Find the Canvas Element

To find the canvas element use the HTML DOM method: getElementById():

Canvas Drawing

var canvas=document.getElementById("canvas");

2. Create a drawing object

Use the getContext() method to get a drawing context, which provides properties and methods:

Canvas Drawing

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

3. Draw on the Canvas Element

Now you can draw on the canvas. The fillStyle property can be a CSS color, a pattern, or a gradient.

Canvas Drawing

ctx.fillStyle = "#1c87c9";

You can also use the fillRect(x, y, width, height) method to draw a filled rectangle on the canvas. The parameters specify the x and y coordinates of the top-left corner, followed by the width and height:

Canvas Drawing

ctx.fillRect(0, 0, 230, 130);

Example of the HTML <canvas> tag:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <canvas id="canvas" width="250" height="150" style="border:1px solid #dddddd;">
      The canvas tag is not supported by your browser.
    </canvas>
    <script>
      var canvas = document.getElementById("canvas");
      var ctx = canvas.getContext("2d");
      ctx.fillStyle = "#1c87c9";
      ctx.fillRect(0, 0, 230, 130)
    </script>
  </body>
</html>

Practice

Practice

What are the elements required to draw on HTML canvas?