<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>蚂蚁线</title> </head> <body> <canvas id="canvas"></canvas> </body> <script> var canvas = document.getElementById('canvas'), context = canvas.getContext('2d'); offset = 0.0; context.setLineDash([5,5]); /** * 画虚线矩形,并调整偏移量 */ function antChange() { offset+=3.0; context.lineDashOffset=offset; context.beginPath(); context.rect(10,10,100,100); context.stroke(); } /** * 清除之前的图像 */ function clear(){ context.clearRect(0,0,canvas.width,canvas.height); } /** * 画蚂蚁线 */ function antLine(){ clear(); antChange(); } setInterval(antLine,200); </script> </html>