gpt4 book ai didi

javascript - 如何停止或暂停该程序?

转载 作者:行者123 更新时间:2023-12-03 07:56:01 25 4
gpt4 key购买 nike

我尝试使用clearTimeout,但失败了,谁能告诉我如何停止或暂停这个动画?下面是我的 JavaScript 代码:

window.requestAnimFrame = (function(callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();

function drawRectangle(myRectangle, context) {
context.beginPath();
context.rect(myRectangle.x, myRectangle.y, myRectangle.width, myRectangle.height);
context.fillStyle = 'green';
context.fill();
context.lineWidth = myRectangle.borderWidth;
context.strokeStyle = 'black';
context.stroke();
}

function myFunction() {
var m = document.getElementById("myRange").value;
document.getElementById("demo").innerHTML = m;
}

function animate(myRectangle, canvas, context, startTime) {

var time = (new Date()).getTime() - startTime;
var m = document.getElementById("myRange").value;
myRectangle.y = 380 - m * Math.cos(time * Math.PI / 2000);
context.clearRect(0, 0, canvas.width, canvas.height);
drawRectangle(myRectangle, context);

requestAnimFrame(function() {
animate(myRectangle, canvas, context, startTime);
});
}

var myRectangle = {
x: 150,
y: 150,
width: 50,
height: 50,
borderWidth: 4
};

drawRectangle(myRectangle, context);

setTimeout(function() {
var startTime = (new Date()).getTime();
animate(myRectangle, canvas, context, startTime);
}, 0);

最佳答案

您的回调应该停止调用 requestAnimationFrame

var stop = false;
function stopAnimation() {
stop = true;
}

function animate(myRectangle, canvas, context, startTime) {

// ...

if (stop) {
stop = false;
}
else {
requestAnimFrame(function() {
animate(myRectangle, canvas, context, startTime);
});
}
}

关于javascript - 如何停止或暂停该程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34799720/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com