我试图创建一种交互式地图。用户在画布上放置标记以标记通过地图的路径。一旦他们完成了我希望他们能够按下一个按钮来设置他们的路径,一次一个标记,但我似乎无法弄清楚如何做到这一点。
我让用户使用此代码标记画布。
getCoords(e)是放置在别处的函数,用于检测鼠标坐标。
function draw(e) //mousemove
{
context.clearRect(0,0,canvas.width,canvas.height, false);
var coords = getCoords(e);
a = coords[0];
b = coords[1];
xcor.push(a);
xcor.push(b);
context.moveTo(coords[0], coords[1]);
context.beginPath();
context.arc
(
coords[0],
coords[1],
10,
Math.PI*2,
false
);
context.closePath();
context.fillStyle='blue';
context.fill();
if (drawing == true)
{
for(i=0;i<drawCoords.length;i++)
{
context.beginPath();
context.arc
(
drawCoords[i].x,
drawCoords[i].y,
10,
Math.PI*2,
false
);
context.closePath();
context.fill();
x = coords[0];
y = coords[1];
context.beginPath();
for(i=0;i<drawCoords.length;i++)
{
context.lineTo(drawCoords[i].x,drawCoords[i].y);
context.stroke();
}
}
function startSketch(e) //mousedown
{
var coords = getCoords(e);
drawCoords.push({x:coords[0], y:coords[1]});
draw();
}
然后我尝试循环遍历该代码,以便在使用此代码单击按钮时为该路径设置动画。
function playButton()
{
drawing = false;
context.clearRect(0,0,canvas.width,canvas.height, false);
(function theLoop (l)
{
setTimeout(function ()
{
draw();
if (--l)
{
theLoop(l);
}
}, 1000);
})(drawCoords.length);
}
它显示已完成的路径但我希望它显示每个步骤之间有延迟。
我想我可能在theLoop函数中使用了错误的数组drawCoords,但我似乎无法找出循环遍历数组内容的方法。我试过从draw()重写大部分代码;在setTimeout函数中,但是当我这样做时,什么都没发生。
如果有人能帮助我,我真的很感激。非常感谢。
答案 0 :(得分:0)
当函数重复时,会立即触发setTimeout。您可以使用setInterval来实现此目的。如果您需要更高质量的动画,请查看requestAnimationFrame()。
var i = 1;
var animation = setInterval(function() {
draw();
i += 1;
if(i >= drawCoords.length) {
clearInterval(animation);
}
}, 1000);