我不明白为什么cancelAnimationFrame方法不取消requestAnimationFrame。它仍然在控制台上记录消息。有谁能解释一下吗?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="description" content="Interaktywny poradnik szybkiego startu dla Brackets.">
<link rel="stylesheet" href="test.css">
</head>
<body>
<div class="box1" style="height:100px;width:100px;background:red">
</div>
</body>
<script>
let container;
container = document.getElementsByClassName('box1')[0];
let increase=0
let animate;
function increaseHeight(){
increase = increase + 2;
container.style.height=increase + "px";
if(increase>200){
console.log("cancelAnimation");
cancelAnimationFrame(animate)
}
animate = requestAnimationFrame(increaseHeight);
}
increaseHeight();
</script>
</html>发布于 2019-11-17 05:33:52
我觉得你真正想做的是
const container = document.getElementsByClassName('box1')[0];
let increase = 0;
function increaseHeight() {
if (increase < 200) {
increase = increase + 2;
container.style.height = increase + "px";
requestAnimationFrame(increaseHeight); // continue animation
} else {
console.log("stopping animation");
}
}
increaseHeight();不需要取消。
发布于 2019-11-17 05:34:32
它不是取消,因为在取消已经运行的帧之后,您正在请求新的帧。您需要将新的帧请求放入if(increase<200){块中。另外,你实际上不应该取消任何事情。一个动画帧请求只运行一次,如果你想运行另一个,你必须请求另一个。所以,当你的动画制作完成后,只要不要求另一个动画,你就会做得很好。
https://stackoverflow.com/questions/58895395
复制相似问题