我有这个功能来创建一个删除框的动画:
function dropBox(y, width, height) {
var img_box = new Image();
img_box.src = 'images/gift_box_small.png';
var box_y_pos = y;
if(y==0)
box_y_pos = y-img_box.naturalHeight;
img_box.onload = function(){
ctx_overlay.save();
ctx_overlay.clearRect(0,0,width,height);
ctx_overlay.drawImage(img_box, (width/2)-(img_box.naturalWidth/2), box_y_pos);
ctx_overlay.restore();
}
box_y_pos += 3;
var loopTimer = setTimeout(function() {dropBox(box_y_pos, width, height)},24);
}
我想在框到达某个Y位置时停止动画并调用其他功能。我无法在setTimeout声明之前检查Y位置的代码,因为它还没有被声明,之后我就无法使用它,因为它无法访问。那怎么办呢?
答案 0 :(得分:0)
只需将stop_y位置的额外变量传递给函数即可。并且仅当框未到达此位置时才调用setTimeout():
function dropBox(y, width, height, stop_y) {
var img_box = new Image();
img_box.src = 'http://corkeynet.com/test/images/gift_box_small.png';
var box_y_pos = y;
if(y==0)
box_y_pos = y-img_box.naturalHeight;
img_box.onload = function(){
ctx_overlay.save();
ctx_overlay.clearRect(0,0,width,height);
ctx_overlay.drawImage(img_box, (width/2)-(img_box.naturalWidth/2), box_y_pos);
ctx_overlay.restore();
}
box_y_pos += 3;
if (box_y_pos < stop_y) {
var loopTimer = setTimeout(function() {dropBox(box_y_pos, width, height, stop_y)},24);
}
}
在此处编辑您的代码:http://jsfiddle.net/93jwqf2j/