How to draw on the canvas with JavaScript?


Drawing on the HTML canvas is to be done with JavaScript. Use the HTML DOM Method getElementById() and getContext() before drawing on the canvas.

For that, follow some steps −

  • You need to use the getElementById() method to find the canvas element.
  • Use the getContext(), which is drawing object for the canvas. It provides the methods and properties for drawing.
  • After that draw on the canvas.

Example

You can try to run the following code to draw canvas on JavaScript −

<!DOCTYPE html>
<html>
   <head>
      <title>HTML Canvas</title>
   </head>
   <body>
      <canvas id="newCanvas" width="400" height="250" style="border:2px solid #000000;"></canvas>
      <script>
         var canvas = document.getElementById("newCanvas");
         var ctxt = canvas.getContext("2d");
         ctxt.fillStyle = "#56A7E2";
         ctxt.fillRect(0,0,250,120);
      </script>
   </body>
</html>

Updated on: 15-Jun-2020

514 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements