The following code shows how to draw a line in html5 canvas.
<!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>
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:
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.