Skip to content

Canvas Drawing

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

javascript
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

javascript
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

javascript
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

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

Example of the HTML <canvas> tag:

Example of the HTML <canvas> tag

html
<!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

What are the elements required to draw on HTML canvas?

Dual-run preview — compare with live Symfony routes.