13
The HTML5 <canvas> element provides tools for drawing lines using the CanvasRenderingContext2D API.
Lines are created as part of paths, which can be styled, connected, and manipulated for various visual effects.
1. Understanding Lines in Canvas
To draw a line:
- Start a path with beginPath().
- Use moveTo(x, y) to set the starting point.
- Use lineTo(x, y) to define the endpoint(s).
- Draw the line using stroke().
2. Basic Line Drawing
Example 1: Drawing a Single Line
<canvas id="myCanvas" width="500" height="300" style="border: 1px solid black;"></canvas> <script> const canvas = document.getElementById("myCanvas"); const ctx = canvas.getContext("2d"); // Start the path ctx.beginPath(); ctx.moveTo(50, 50); // Starting point ctx.lineTo(200, 150); // Ending point ctx.strokeStyle = "blue"; // Line color ctx.lineWidth = 3; // Line thickness ctx.stroke(); // Render the line </script>
Explanation:
- beginPath(): Starts a new drawing path.
- moveTo(x, y): Moves the pen to a starting point without drawing.
- lineTo(x, y): Draws a straight line to the specified point.
- stroke(): Renders the line.
3. Drawing Multiple Lines
You can create more complex shapes by chaining multiple lineTo calls.
Example 2: Connecting Lines
ctx.beginPath(); ctx.moveTo(50, 50); ctx.lineTo(150, 50); ctx.lineTo(150, 150); ctx.lineTo(50, 150); ctx.closePath(); // Connects back to the starting point ctx.strokeStyle = "red"; ctx.lineWidth = 2; ctx.stroke();
Explanation:
- closePath(): Closes the path by connecting the last point to the starting point.
4. Customizing Line Styles
You can customize lines with properties like:
- lineWidth: Sets the thickness of the line.
- strokeStyle: Sets the line color.
- lineCap: Defines the style of line endings.
- lineJoin: Defines how lines connect at their corners.
Example 3: Custom Line Styles
// Line with different cap styles ctx.beginPath(); ctx.moveTo(50, 100); ctx.lineTo(150, 100); ctx.lineCap = "butt"; // Options: butt, round, square ctx.strokeStyle = "black"; ctx.lineWidth = 5; ctx.stroke(); ctx.beginPath(); ctx.moveTo(200, 100); ctx.lineTo(300, 100); ctx.lineCap = "round"; ctx.stroke(); ctx.beginPath(); ctx.moveTo(350, 100); ctx.lineTo(450, 100); ctx.lineCap = "square"; ctx.stroke();
Explanation:
- lineCap: Controls the shape of line endings (butt, round, square).
Example 4: Line Joins
ctx.beginPath(); ctx.moveTo(50, 200); ctx.lineTo(150, 150); ctx.lineTo(250, 200); ctx.lineJoin = "miter"; // Options: miter, bevel, round ctx.strokeStyle = "blue"; ctx.lineWidth = 5; ctx.stroke(); ctx.beginPath(); ctx.moveTo(300, 200); ctx.lineTo(400, 150); ctx.lineTo(500, 200); ctx.lineJoin = "round"; ctx.strokeStyle = "green"; ctx.stroke();
Explanation:
- lineJoin: Determines how corners are drawn when two lines meet (miter, round, bevel).
5. Dotted and Dashed Lines
Use setLineDash() to create patterns of dashes and gaps.
Example 5: Dashed and Dotted Lines
// Dashed line ctx.beginPath(); ctx.setLineDash([10, 5]); // [dash length, gap length] ctx.moveTo(50, 250); ctx.lineTo(450, 250); ctx.strokeStyle = "purple"; ctx.lineWidth = 2; ctx.stroke(); // Dotted line ctx.beginPath(); ctx.setLineDash([2, 2]); ctx.moveTo(50, 300); ctx.lineTo(450, 300); ctx.strokeStyle = "orange"; ctx.stroke();
6. Combining Lines with Other Shapes
Example 6: Drawing a Star
ctx.beginPath(); const centerX = 250; const centerY = 150; const spikes = 5; const outerRadius = 100; const innerRadius = 50; for (let i = 0; i < spikes * 2; i++) { const angle = (i * Math.PI) / spikes; const radius = i % 2 === 0 ? outerRadius : innerRadius; const x = centerX + Math.cos(angle) * radius; const y = centerY + Math.sin(angle) * radius; if (i === 0) { ctx.moveTo(x, y); } else { ctx.lineTo(x, y); } } ctx.closePath(); ctx.strokeStyle = "gold"; ctx.lineWidth = 3; ctx.stroke();
7. Animating Lines
You can create dynamic effects by animating lines.
Example 7: Growing Line Animation
let x = 50; function animateLine() { ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.beginPath(); ctx.moveTo(50, 150); ctx.lineTo(x, 150); ctx.strokeStyle = "blue"; ctx.lineWidth = 3; ctx.stroke(); if (x < 450) { x += 2; // Increase the endpoint } requestAnimationFrame(animateLine); } animateLine();
8. Practical Example: Line Graph
Example 8: Drawing a Line Graph
const data = [50, 100, 150, 120, 180, 140]; const spacing = 70; ctx.beginPath(); ctx.moveTo(50, canvas.height - data[0]); data.forEach((value, index) => { const x = 50 + index * spacing; const y = canvas.height - value; ctx.lineTo(x, y); }); ctx.strokeStyle = "green"; ctx.lineWidth = 2; ctx.stroke(); // Add points data.forEach((value, index) => { const x = 50 + index * spacing; const y = canvas.height - value; ctx.beginPath(); ctx.arc(x, y, 5, 0, Math.PI * 2); ctx.fillStyle = "red"; ctx.fill(); });
9. Best Practices for Drawing Lines
- Use beginPath for New Lines:
- Always call beginPath() before starting a new line to avoid connecting it to previous paths.
- Keep Line Styles Consistent:
- Set properties like strokeStyle, lineWidth, and lineJoin for consistent appearance.
- Optimize Performance:
- Clear only the necessary areas when animating or redrawing.
10. Browser Support
All modern browsers fully support line-related methods in the Canvas API:
Feature | Supported? |
---|---|
beginPath | Yes |
moveTo, lineTo | Yes |
setLineDash | Yes |
strokeStyle, etc. | Yes |
11. Conclusion
In this tutorial, you learned:
- How to draw and style lines using moveTo, lineTo, and stroke.
- How to customize line styles with lineCap, lineJoin, and setLineDash.
- How to animate lines and use them in practical applications like graphs.