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.
Last active
October 25, 2018 11:16
-
-
Save mszkb/80319aae3c23c78c71b42bf3e5d7357d to your computer and use it in GitHub Desktop.
Marching ants
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!-- Learn about this code on MDN: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset --> | |
| <canvas id="canvas" class="playable-canvas"></canvas> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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