Canvas Draw Lines

What You’ll Learn
Lines are the foundation of canvas drawing. You create a path, move the pen to a start point, draw to an end point, then render the stroke.
On this page you’ll learn beginPath(), moveTo(), lineTo(), and the most important stroke style controls.
⚡ Quick Reference
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();lineWidthDefault is 1
lineCapbutt | round | square
lineJoinmiter | round | bevel
setLineDash()Example: [10, 6]
👀 Live Preview — Line Styles
Change line width, cap/join styles, and dashes. The preview draws a path with a corner and a single straight segment so you can see both joins and caps.
Tip: if you see spikes at corners with miter, try round or adjust miterLimit.
Simple Diagonal Line
The minimum set of calls: start a path, choose start/end points, then stroke.
<canvas id="myCanvas" width="420" height="220"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(300, 170);
ctx.strokeStyle = '#0f172a';
ctx.lineWidth = 3;
ctx.stroke();
</script>🧠 How it works
moveTo() sets the starting point. lineTo() adds a straight segment to the path. stroke() renders the outline.
Polyline (Multiple Segments)
Lines become interesting when you connect multiple segments (paths). Joins control the corner look.
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.moveTo(60, 170);
ctx.lineTo(140, 60);
ctx.lineTo(240, 140);
ctx.lineTo(340, 50);
ctx.strokeStyle = '#2563eb';
ctx.lineWidth = 6;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.stroke();💡 Best Practices
Do
- Start each independent line/path with
beginPath() - Set
strokeStyleandlineWidthbeforestroke() - Use
lineCapandlineJoinfor polished visuals - Use
setLineDash([])to reset dashes when you’re done - Snap to half-pixels for crisp 1px lines on low-DPI canvases (optional)
Don’t
- Forget
stroke()(paths don’t render automatically) - Assume dashes only apply to one stroke (they persist)
- Use extreme
miterjoins without a reasonablemiterLimit - Draw outside the canvas without checking coordinates
- Overdraw large canvases every frame without profiling
❓ Frequently Asked Questions
beginPath(), moveTo(), lineTo(), and then stroke().stroke(), you drew outside the canvas, or your style is transparent (or lineWidth is 0).lineCap controls line ends; lineJoin controls corners between connected segments.ctx.setLineDash([dash, gap]) before stroke(). Reset with ctx.setLineDash([]).Continue with Paths
Learn how to combine lines and curves into reusable paths.
4 people found this page helpful
