Canvas Marching Ants Animation

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.

Working marching ants demo Top ↑

Animated dashed selection border.

Core animation code Top ↑

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);

Why requestAnimationFrame() is better than setTimeout() here Top ↑

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.

Common mistakes Top ↑

  • Creating a new timer on every control change.
  • Forgetting to clear and redraw the frame.
  • Using stroke() after strokeRect(); strokeRect() paints immediately.
  • Running decorative motion when the user requests reduced motion.
  • Using zero-length dash and gap controls that make the effect confusing.

Frequently asked questions Top ↑

What creates the marching ants effect? Top ↑

A repeating dash pattern plus a lineDashOffset value that changes over successive animation frames.

Can the direction be reversed? Top ↑

Yes. Increment the offset instead of decrementing it, or vice versa.

Do I need jQuery for this animation? Top ↑

No. Canvas and requestAnimationFrame() are native browser APIs.

Can I change the dash pattern while it runs? Top ↑

Yes. Update setLineDash() values before drawing each frame.

Should the animation always autoplay? Top ↑

Not necessarily. Provide a pause control and respect reduced-motion preferences for nonessential animation.

lineDashOffset | setLineDash() | strokeRect() | JavaScript events | Canvas tutorial





plus2net.com







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.



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