This JavaScript program demonstrates how to animate marching ants via the dash offset on a canvas element.
<!DOCTYPE html> <html> <head> <title>XoaX.net's Javascript</title> <script type="text/javascript" src="MarchingAnts.js"></script> </head> <body onload="Initialize()"> <canvas id="idCanvas" width="640" height ="480" style="background-color: #F0F0F0;"></canvas> </body> </html>
var gqCanvas = null; var gqContext = null; var giOffset = 0; function Initialize() { gqCanvas = document.getElementById("idCanvas"); gqContext = gqCanvas.getContext("2d"); giOffset = 0; Advance(); } function Draw() { gqContext.clearRect(0, 0, gqCanvas.width, gqCanvas.height); gqContext.setLineDash([4, 2, 1, 2, 1, 2]); // This negative sign changes the direction gqContext.lineDashOffset = -giOffset; gqContext.lineWidth = .5; gqContext.strokeRect(250, 170, 140, 140); var dCx = 320.0; var dCy = 240.0; var dRadius = 100.0; var dArcStart = 0.0; var dArcEnd = 2.0*Math.PI; // The direction of the movement depends on the offset and this drawing direction. var bCounterClockwise = true; gqContext.beginPath(); gqContext.arc(dCx, dCy, dRadius, dArcStart, dArcEnd, bCounterClockwise); gqContext.stroke(); } function Advance() { // This can be used to set the direction. giOffset = ((giOffset + 1) % 12); Draw(); setTimeout(Advance, 50); }
© 20072025 XoaX.net LLC. All rights reserved.