HTML5 Game - Drawing a Line

Introduction

The following code shows how to draw a line in html5 canvas.

Demo

ResultView the demo in separate window

<!DOCTYPE html>
<html lang="en">
 <head> 
  <meta charset="UTF-8"> 
  <title>HTML5 Canvas</title> 
  <script type="text/javascript">
    window.onload = function(){//  ww  w.  j  ava2  s . c  om
        let canvas = document.getElementById("myCanvas");
        let context = canvas.getContext("2d");
        // draw stuff here
         context.moveTo(10, 100); 
         context.lineTo(190, 100); 
         context.stroke(); 
        
    };
</script> 
 </head> 
 <body> 
  <canvas id="myCanvas" width="300" height="200"></canvas>   
 </body>
</html>

Note

The context variable holds a reference to a drawing context.

To draw a line with start coordinates of (10,100) and end coordinates of (190,100), you use three methods of the drawing context:

  • moveTo()
  • lineTo()
  • stroke()

The moveTo() method moves the current drawing coordinates to specified x and y points (10 and 100 in this case).

The lineTo() method specifies the end coordinates of the line (190,100 in this case).

The line isn't drawn immediately after you call the lineTo() method.

You inform the drawing context that the drawing operation is to be performed using the stroke() method.

Related Topic