gpt4 book ai didi

javascript - "requestAnimationFrame"方法无效

转载 作者:行者123 更新时间:2023-12-05 04:17:41 26 4
gpt4 key购买 nike

“requestAnimationFrame”方法在以下示例中不起作用。控制台不显示任何错误消息。那么这段代码的错误是什么?HTML:

   <body>
<div id="container">
<canvas id="canvas" width="1024" height="1024"></canvas>
</div>
<script type="text/javascript" src = "Jquery/easy.js"></script>
</body>

JavaScript:

 var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var chop1 = new Image();
chop1.src = "img/chopper.png";
var chopperX = 0;
var chopperY = 0;
var ascent = 20;

function fly()
{
chopperY += ascent;
ctx.drawImage(chop1, chopperX, chopperY, 30, 80);
requestAnimationFrame(fly);

}

window.onload = function() {
init()
};

function init()
{
chop1.src = "img/chopper.png";
ctx.drawImage(chop1, 0, 0, 30, 80);
fly()
}
;

最佳答案

您可能希望使用传递给 requestAnimationFrame 的回调的 timestamp 来缩放动画。使用这样的东西:

var ascent = 20;
var limit = 5000;
var start = null;

function fly(timestamp) {
if (start === null) {
start = timestamp;
}
var progress = timestamp - start;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(chop1, 0, Math.min(progress / ascent, canvas.height),
chop1.width, chop1.height);
if (progress < limit) {
requestAnimationFrame(fly);
}
}

requestAnimationFrame(fly);

您可以修改 ascentlimit 来增加/减少动画的速度和最终位置。

正如其他人提到的,一定要使用正确的requestAnimationFrame:

window.requestAnimationFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame;

更多信息:

关于javascript - "requestAnimationFrame"方法无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21139826/

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