Canvas Drawing

The JavaScript should be used to draw on the canvas. We are going to do with step by step.

1. Find the Canvas Element

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

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

2. Create a drawing object

Use the getContext() HTML object, with properties and methods:

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

3. Draw on the Canvas Element

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

ctx.fillStyle = "#1c87c9";

You can also use the fillRect (x, y, width, height) method that draws a rectangle that is filled with the fill style, on the canvas:

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 Your Knowledge

What are the elements required to draw on HTML canvas?

Quiz Time: Test Your Skills!

Ready to challenge what you've learned? Dive into our interactive quizzes for a deeper understanding and a fun way to reinforce your knowledge.

Do you find this helpful?