Marching Ants
Show marching ants on an image.
by ksoncan34
HTML
<canvas id="MyCanvas" width="500" height="400">
</canvas>
JavaScript
var dashList = [12, 3, 3, 3]; // Create a dot/dash sequence
var antOffset = 0; // Starting offset value
var canvas = document.getElementById("MyCanvas");
var ctx = canvas.getContext("2d");
var img = new Image();
img.addEventListener('load', function() {
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0,0);
});
img.src = 'https://placekitten.com/500/400';
function draw() {
if (canvas.getContext) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (ctx.setLineDash) {
// Assign the dashList for the dash sequence
ctx.setLineDash(dashList);
// Get the current offset
ctx.lineDashOffset = antOffset; // To animate the lines
ctx.lineJoin = "round";
ctx.lineWidth = "3";
ctx.strokeStyle = "blue";
ctx.drawImage(img, 0,0);
ctx.strokeRect(5, 5, 300, 250);
}
}
}
// Marching Ant code
function doAnts() {
antOffset++;
if (antOffset > 20) // Reset offset after total of dash List values
{
antOffset = 0;
}
draw();
setTimeout(doAnts, 10); // Set a leisurely march of 10ms
}
doAnts(); // Start the demo