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.
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();
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);
}
lineDashOffset() as a function. It is a property.Yes. Positive and negative numeric offsets are valid and move the repeating dash phase in opposite directions.
No. Dash and gap lengths come from setLineDash(); lineDashOffset only changes the starting phase.
The dash pattern repeats. Offsets separated by a complete pattern cycle can produce the same visual result.
Common uses include animated selection borders, moving dashed paths and adjusting where a dashed outline begins.
Call setLineDash([]). The offset then has no visible effect on the solid stroke.
setLineDash() | Marching ants | lineWidth | strokeStyle | Canvas tutorial
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.