Canvas Coordinates

The HTML canvas is considered to be a two-dimensional grid, the upper-left corner of which has the coordinates (0,0).

Drawing a Line

The methods below are used to draw a straight line on a canvas:

  • moveTo(x,y), which specifies the starting point of the line
  • lineTo(x,y), which specifies the ending point of the line

Use one of the "ink" methods to draw a line, for example, the stroke().

Example of the HTML <canvas> element to draw a line:

<!DOCTYPE html>
<html>
  <body>
    <canvas  width="300" height="150" style="border:1px solid #cccccc;" id="canvasExample">
      Your browser does not support the HTML5 canvas tag.
    </canvas>
    <script>
      var c=document.getElementById("canvasExample");
      var ctx=c.getContext("2d");
      ctx.moveTo(0,0);
      ctx.lineTo(300,150);
      ctx.strokeStyle='#359900';
      ctx.stroke();
    </script>
  </body>
</html>

In the example above, we have defined the starting and ending points of the line, that we have used the stroke() method to draw it.

Drawing a Circle

The methods below are used to draw a circle on a canvas:

  • beginPath(), which begins a path
  • arc(x,y,r,startangle,endangle), which creates an arc/curve. If you want to create a circle with arc(): set start angle to 0 and end angle to 2*Math.PI. The x and y specify the x- and y-coordinates of the circle’s center. The r parameter specifies the radius of the circle.

Example of the HTML <canvas> element to draw a circle:

<!DOCTYPE html>
<html>
  <body>
    <canvas id="exampleCanvas" width="250" height="200" style="border:1px solid #dddddd;">
      The canvas tag is not supported by your browser..
    </canvas>
    <script>
      var canvas=document.getElementById("exampleCanvas");
      var ctx=canvas.getContext("2d");
      ctx.beginPath();
      ctx.arc(125,95,70,0,2*Math.PI);
      ctx.strokeStyle='#1c87c9';
      ctx.stroke();
    </script> 
  </body>
</html>

In the example above, we have defined a circle with the arc() method and used the stroke() method to draw the circle.




Do you find this helpful?

Related articles