Skip to content

Instantly share code, notes, and snippets.

@mszkb
Last active October 25, 2018 11:16
Show Gist options
  • Select an option

  • Save mszkb/80319aae3c23c78c71b42bf3e5d7357d to your computer and use it in GitHub Desktop.

Select an option

Save mszkb/80319aae3c23c78c71b42bf3e5d7357d to your computer and use it in GitHub Desktop.
Marching ants
<!-- Learn about this code on MDN: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset -->
<canvas id="canvas" class="playable-canvas"></canvas>

Marching ants

This is a modified version of marching ants animation of Mozilla MDN web docs. It makes use of window.requestAnimationFrame for better performance and removes the ugly setTimout workaround.

A Pen by MSZ on CodePen.

License.

// Source:
// - original .. https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset
// - modified with help of .. https://blog.teamtreehouse.com/efficient-animations-with-requestanimationframe
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var offset = 0;
function draw() {
  ctx.clearRect(0,0, canvas.width, canvas.height);
  ctx.setLineDash([4, 2]);
  ctx.lineDashOffset = -offset;
  ctx.strokeRect(10, 10, 100, 100);
}
function march() {
window.requestAnimationFrame(march); // edit: at beginning for max fps
  offset++;
  if (offset > 16) {
    offset = 0;
  }
  draw();
}
window.requestAnimationFrame(march); // edit: start the animation
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment