HTML Canvas Draw Lines

Beginner
7 min read
Updated: Nov 2026
5 examples
Live preview

Definition

On an <canvas>, straight lines are path segments. Use moveTo() to place the pen, lineTo() to add a segment, then stroke() to paint it.

Style lines with lineWidth, strokeStyle, lineCap, lineJoin, and setLineDash(). Start each separate stroke with beginPath(). For richer shapes, continue with paths, arcs, and curves.

Baseline · Widely available.

moveTo(), lineTo(), and stroke() are stable Canvas 2D features across modern browsers since about July 2015.

Path first, paint second.

lineTo() does not draw by itself. Always finish with stroke() (or fill() for closed shapes).

Syntax

line.js
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();

Chain more lineTo() calls for a polyline. Use closePath() when you want the last point to connect back to the first.

Key Methods & Properties

Core line tools on the 2D context:

NameDescriptionTry it
moveTo(x, y)Move the pen without drawingTry it
lineTo(x, y)Add a straight segment to (x, y)Try it
stroke()Paint the current path outlineTry it
lineWidthStroke thickness (default 1)Try it
lineCapbutt | round | squareTry it
setLineDash([...])Dash pattern, e.g. [8, 4]Try it
lineJoinCorner style: miter, round, bevelSee edge cases

Global Attributes

The <canvas> tag also supports the Global Attributes in HTML.

Live Preview

Change thickness and end caps, then toggle a dash pattern on a single stroked line.

8

Gray guides show the true endpoints so you can compare cap styles.

Canvas

lineWidth=8 lineCap="round"

HTML Examples

Short, copy-ready snippets. Use Try It Yourself for a live editor.

Example 1 — Basic Straight Line

The four-step pattern: path, move, line, stroke.

HTML
<canvas id="demo" width="300" height="120" aria-label="Blue straight line"></canvas>
<script>
  const ctx = document.getElementById("demo").getContext("2d");
  ctx.beginPath();
  ctx.moveTo(30, 60);
  ctx.lineTo(270, 60);
  ctx.strokeStyle = "#2563eb";
  ctx.lineWidth = 3;
  ctx.stroke();
</script>
Try It Yourself

How It Works

  1. Start a path with beginPath().
  2. Place the pen with moveTo(30, 60).
  3. Add a segment with lineTo(270, 60).
  4. Paint with stroke() after setting color and width.

Example 2 — Connected Lines (Triangle)

Chain lineTo calls, then closePath to seal the shape.

HTML
<canvas id="demo" width="300" height="160" aria-label="Stroked triangle"></canvas>
<script>
  const ctx = document.getElementById("demo").getContext("2d");
  ctx.beginPath();
  ctx.moveTo(150, 30);
  ctx.lineTo(250, 130);
  ctx.lineTo(50, 130);
  ctx.closePath();
  ctx.strokeStyle = "#0f172a";
  ctx.lineWidth = 3;
  ctx.stroke();
</script>
Try It Yourself

How It Works

  1. moveTo sets the first corner.
  2. Two lineTo calls add the other sides.
  3. closePath() draws the last side back to the start.
  4. stroke() outlines the whole triangle in one paint.

Example 3 — Thickness and Color

Set lineWidth and strokeStyle before stroking.

HTML
<canvas id="demo" width="300" height="140" aria-label="Three lines with different widths"></canvas>
<script>
  const ctx = document.getElementById("demo").getContext("2d");
  const widths = [2, 6, 12];
  const colors = ["#2563eb", "#16a34a", "#dc2626"];

  for (let i = 0; i < widths.length; i++) {
    ctx.beginPath();
    ctx.moveTo(30, 30 + i * 40);
    ctx.lineTo(270, 30 + i * 40);
    ctx.lineWidth = widths[i];
    ctx.strokeStyle = colors[i];
    ctx.stroke();
  }
</script>
Try It Yourself

How It Works

  1. Loop three times — one stroke per line.
  2. Call beginPath() each time so styles do not merge oddly.
  3. Assign lineWidth and strokeStyle before stroke().
  4. Offset the Y position so the lines do not overlap.

Example 4 — lineCap Styles

Compare butt, round, and square ends on thick lines.

HTML
<canvas id="demo" width="300" height="160" aria-label="Three lineCap styles"></canvas>
<script>
  const ctx = document.getElementById("demo").getContext("2d");
  const caps = ["butt", "round", "square"];

  for (let i = 0; i < caps.length; i++) {
    const y = 35 + i * 45;
    ctx.beginPath();
    ctx.moveTo(60, y);
    ctx.lineTo(240, y);
    ctx.lineWidth = 16;
    ctx.lineCap = caps[i];
    ctx.strokeStyle = "#334155";
    ctx.stroke();
  }
</script>
Try It Yourself

How It Works

  1. Use a large lineWidth so cap differences are obvious.
  2. butt stops exactly at the endpoint.
  3. round adds a semicircle; square extends past the tip.
  4. Set lineCap before each stroke().

Example 5 — Dashed Line

Use setLineDash for a dash–gap pattern.

HTML
<canvas id="demo" width="300" height="120" aria-label="Orange dashed line"></canvas>
<script>
  const ctx = document.getElementById("demo").getContext("2d");
  ctx.beginPath();
  ctx.moveTo(30, 60);
  ctx.lineTo(270, 60);
  ctx.lineWidth = 4;
  ctx.strokeStyle = "#ea580c";
  ctx.setLineDash([12, 8]);
  ctx.stroke();
  ctx.setLineDash([]);
</script>
Try It Yourself

How It Works

  1. Build a normal line path with moveTo / lineTo.
  2. Call setLineDash([12, 8]) — 12px dash, 8px gap.
  3. Stroke while the dash pattern is active.
  4. Reset with setLineDash([]) so later strokes are solid.

Edge Cases & Pitfalls

Most blank lines come from a missing stroke() or leftover dash/cap state.

paint

lineTo is not a paint call

The path stays invisible until stroke() (or fill() on a closed path).

path

Use beginPath() for separate strokes

Without it, new segments attach to the previous path and share one stroke.

state

Dash and cap persist

Reset with setLineDash([]) and set lineCap back to "butt" when needed. Prefer save()/restore().

joins

lineJoin needs corners

miter, round, and bevel only show at corners of connected segments — not on a single straight line.

half-pixel

1px lines can look blurry

For crisp 1px horizontals/verticals, try half-pixel coords (e.g. y + 0.5) so the stroke sits on a pixel boundary.

Browser Support

moveTo(), lineTo(), stroke(), and line styling are part of the Canvas 2D API in every modern browser.

✓ Baseline · Widely available

lineTo()

Widely available since about July 2015. Chrome, Firefox, Safari, Edge, and Opera support straight lines, caps, joins, and dashes. Internet Explorer 9+ supports core line drawing.

98% Global support (approx.)
Google Chrome All modern
Full support
Mozilla Firefox All modern
Full support
Apple Safari All modern
Full support
Microsoft Edge All modern
Full support
Opera All modern
Full support
Samsung Internet All modern
Full support
Internet Explorer 9+
Supported
lineTo / stroke Widely supported

Bottom line: Safe to use for charts, UI strokes, and diagrams everywhere modern Canvas 2D runs.

Key Takeaways

  • Pattern: beginPath → moveTo → lineTo → stroke.
  • Style: lineWidth, strokeStyle, lineCap, setLineDash.
  • Chain: more lineTo calls build a polyline; closePath seals it.
  • Cleanup: reset dash/cap or use save()/restore().

One line: a canvas line is a stroked path from moveTo to lineTo.

Default CSS Settings

Line drawing is a Canvas API concern. The <canvas> element still uses typical user-agent CSS:

default.css
canvas {
  display: inline;
}

Set bitmap size with HTML width/height. CSS-only sizing scales the bitmap and can blur thin strokes.

Frequently Asked Questions

Call beginPath(), moveTo(x1, y1), lineTo(x2, y2), then stroke(). lineTo only adds to the path; stroke paints it.
moveTo lifts the pen to a point without drawing. lineTo adds a straight segment from the current point to (x, y).
Common causes: forgetting stroke(), strokeStyle matching the background, lineWidth of 0, or never calling beginPath/moveTo so the path is empty.
Set ctx.lineWidth to a positive number (default is 1) before stroke().
lineCap sets the end style: butt (default flush end), round (semicircle), or square (extends half lineWidth past the tip).
Call setLineDash([dash, gap]) before stroke(), for example setLineDash([8, 4]). Use setLineDash([]) to clear dashes.

Next: Draw Rectangles

Learn fillRect and strokeRect for quick boxes without a full path.

Canvas Draw Rectangles →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful