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.


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

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