我真正想要完成的是让形状在按下按钮时停止。截至目前,当用户按下动画时,形状将继续向边界的右下角移动。我正在尝试输入一个按钮来停止由于递归移动功能而发生的动画。我正在尝试使用 stopObj 和 stop 函数,但我的尝试都不起作用。如果有人知道我应该如何编写这个函数来让动画停止,我将不胜感激。
这是有问题的代码:
function setNewPosition(objID, dx, dy) { //This sets the new position of the object
var obj = getElement(objID);
boundaryCheck(objID, dx, dy);
var newleft = parseInt(obj.style.left) + dx;
var newtop = parseInt(obj.style.top) + dy;
obj.style.left = newleft.toString() + 'px';
obj.style.top = newtop.toString() + 'px';
}
function shape(objID, canvasID, dx, dy, delay) {
var thisShape = this;
this.objID = objID;
this.dx = dx;
this.dy = dy;
this.speedX = 0;
this.speedY = 0;
thisShape.draw = function() {
drawShape(canvasID);
}
thisShape.move = function() {
setNewPosition(objID, dx, dy);
setTimeout(thisShape.move, delay);
}
thisShape.stop = function() {
clearTimeout(thisShape.move);
}
}
function moveObj(id) { //starts process to move the shapes.
document.shapeObj[id].move();
}
function stopObj(id){
document.shapeObj[id].stop();
}
就像我说的,问题区域与形状函数内的 thisShape.move 和 thisShape.stop 函数有关。当按下按钮时,我似乎无法让对象真正停止。 感谢您抽出时间。
最佳答案
您正在调用 clearTimeout(thisShape.move);
,但 thisShape.move
是 未定义
,因为您的函数不返回任何内容。
我确信有一个很好的方法可以使用递归函数来做到这一点,但使用专为此类事情设计的 setInterval()
似乎更容易。您可以返回并保存间隔。然后当你想停止时,将其传递给 stopInterval()
例如:
const delay = 1000
function Shape() {
this.count = 0;
this.startMove = () => this.moveInterval = setInterval(this.move, delay);
this.move = () => {
console.log("moving: ", this.count)
this.count++
}
this.stopMove = function() {
console.log("stopping")
clearInterval(this.moveInterval);
}
}
let sh = new Shape()
sh.startMove()
function stop() {
sh.stopMove()
}
<input type="button" onclick=stop() value="stop">
(p.s.我将您的函数声明转换为箭头 =>
函数,以允许在回调中使用 this
并使代码更清晰。)
关于javascript - 对象移动程序 - 无法通过停止动画按钮来停止递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49263127/