How to Draw a Line on Canvas in HTML5
To draw a line on a canvas, use the
CanvasRenderingContext2D methods: start with beginPath(), move the pen with moveTo(x, y), draw the line with lineTo(x, y), and finish with stroke() to display it.Syntax
Here is the basic syntax to draw a line on a canvas:
beginPath(): Starts a new path to draw.moveTo(x, y): Moves the drawing pen to the starting point (x, y).lineTo(x, y): Draws a line from the current point to the new point (x, y).stroke(): Actually draws the line on the canvas.
javascript
const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.moveTo(50, 50); // start point ctx.lineTo(200, 50); // end point ctx.stroke();
Example
This example shows a simple horizontal line drawn on a canvas element.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Draw Line on Canvas</title> <style> canvas { border: 1px solid #ccc; } </style> </head> <body> <canvas id="myCanvas" width="300" height="150" aria-label="Canvas showing a horizontal line"></canvas> <script> const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.moveTo(20, 75); // start point ctx.lineTo(280, 75); // end point ctx.stroke(); </script> </body> </html>
Output
A 300x150 canvas with a single horizontal black line across the middle.
Common Pitfalls
Common mistakes when drawing lines on canvas include:
- Not calling
beginPath()before drawing, which can cause lines to connect unexpectedly. - Forgetting to call
stroke(), so the line does not appear. - Using coordinates outside the canvas size, making the line invisible.
- Not setting the canvas size or style properly, causing layout issues.
javascript
const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d'); // Wrong: missing beginPath and stroke ctx.moveTo(10, 10); ctx.lineTo(100, 10); // Right way ctx.beginPath(); ctx.moveTo(10, 10); ctx.lineTo(100, 10); ctx.stroke();
Quick Reference
Remember these key steps to draw a line on canvas:
- Start path:
beginPath() - Move pen:
moveTo(x, y) - Draw line:
lineTo(x, y) - Show line:
stroke()
Key Takeaways
Always call beginPath() before drawing a new line to avoid unwanted connections.
Use moveTo(x, y) to set the starting point of the line.
Use lineTo(x, y) to define the end point of the line.
Call stroke() to actually draw the line on the canvas.
Make sure your coordinates are within the canvas size to see the line.