A “marching ants” border is a dashed outline whose dash phase moves over time. On Canvas, combine setLineDash(), lineDashOffset, and requestAnimationFrame().
The demo below uses vanilla JavaScript and pauses automatically when the user prefers reduced motion.
ctx.setLineDash([8, 6]);
let offset = 0;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.lineDashOffset = offset--;
ctx.strokeRect(40, 35, 400, 145);
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
requestAnimationFrame() synchronizes visual updates with the browser's rendering cycle and is normally the better choice for Canvas animation. Keep a pause control for long-running animation and consider prefers-reduced-motion when the motion is not essential.
stroke() after strokeRect(); strokeRect() paints immediately.A repeating dash pattern plus a lineDashOffset value that changes over successive animation frames.
Yes. Increment the offset instead of decrementing it, or vice versa.
No. Canvas and requestAnimationFrame() are native browser APIs.
Yes. Update setLineDash() values before drawing each frame.
Not necessarily. Provide a pause control and respect reduced-motion preferences for nonessential animation.
lineDashOffset | setLineDash() | strokeRect() | JavaScript events | 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.
14-01-2023 | |
| Hi, nice demo, but if (offset <1) { offset = 10; } // should be line + gap instead of 10 if (offset >10) { offset = 0; } // should also be line + gap instead of 10 otherwise you get jumps in the animation. | |