Canvas lineDashOffset: Move a Dashed Line Pattern

lineDashOffset shifts where a dashed stroke pattern begins along a Canvas path. Use it after setLineDash() to move the pattern without changing the dash and gap lengths.

The value is a number and may be positive, zero, or negative. Because the dash pattern repeats, offsets separated by one full pattern cycle can look identical.

Canvas dashed line showing dash length, gap and lineDashOffset

Basic lineDashOffset example Top ↑

const canvas = document.getElementById('dash_offset_canvas');
const ctx = canvas.getContext('2d');
ctx.setLineDash([12, 8]);
ctx.lineDashOffset = -6;
ctx.beginPath();
ctx.moveTo(20, 80);
ctx.lineTo(480, 80);
ctx.stroke();
Dashed line offset example.

Interactive dash offset demo Top ↑

Interactive dashed line.

Animating lineDashOffset Top ↑

Changing only the offset on each animation frame creates the familiar moving-dash or “marching ants” effect. The next tutorial provides the complete animation.

function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.lineDashOffset -= 1;
  ctx.strokeRect(20, 20, 300, 120);
  requestAnimationFrame(animate);
}

Common mistakes Top ↑

  • Calling lineDashOffset() as a function. It is a property.
  • Changing the offset without first setting a dash pattern.
  • Assuming the useful offset range is limited to the pattern length. Larger or negative values are valid; the visual pattern simply repeats.
  • Using a fast perpetual animation without respecting reduced-motion preferences.

Frequently asked questions Top ↑

Can lineDashOffset be negative? Top ↑

Yes. Positive and negative numeric offsets are valid and move the repeating dash phase in opposite directions.

Does lineDashOffset change dash length? Top ↑

No. Dash and gap lengths come from setLineDash(); lineDashOffset only changes the starting phase.

Why do different offsets sometimes look the same? Top ↑

The dash pattern repeats. Offsets separated by a complete pattern cycle can produce the same visual result.

What is lineDashOffset used for? Top ↑

Common uses include animated selection borders, moving dashed paths and adjusting where a dashed outline begins.

How do I make a solid line again? Top ↑

Call setLineDash([]). The offset then has no visible effect on the solid stroke.

setLineDash() | Marching ants | lineWidth | strokeStyle | Canvas tutorial





plus2net.com










We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2026   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer