gpt4 book ai didi

javascript - Canvas 动画(window.requestAnimationFrame)

转载 作者:行者123 更新时间:2023-12-03 03:04:59 24 4
gpt4 key购买 nike

所以我是一个 Canvas 新手,我编写了一些代码来尝试创建动画。我想用抛物线方程使球移动,一切正常,除了我基本上得到的是由弧线组成的抛物线,而不是动画。

这是我用于动画的代码片段:

// a b c are calculated in another function and they are used to calculate the parabola, x1 and y1 are the coordinates of the ball
function drawball(a,b,c,x1,y1){
canvas=document.getElementById("mycanvas");
ctx=canvas.getContext("2d");
ctx.beginPath();
ctx.arc(x1,y1,25,0,2*Math.PI);
ctx.stroke();
//stop when i get to the final point (x3 is a const)
if(x1<x3){
y1=a*(x1*x1)+b*x1+c; //parabola formula
x1++;
window.requestAnimationFrame(drawball(a,b,c,x1,y1));
}
}

在 Chrome 的控制台中我收到此错误:

Failed to execute 'requestAnimationFrame' on 'Window': The callback
provided as parameter 1 is not a function.

感谢您的帮助!

最佳答案

您正在尝试将drawball函数的返回值传递到requestAnimationFrame回调中(这是未定义的>)。

下面是 Chrome 控制台中的一个示例,当您尝试将不是函数的值传递给 requestAnimationFrame

> requestAnimationFrame(console.log('hi'))

VM82:1 Uncaught TypeError: Failed to execute 'requestAnimationFrame' on 'Window': The callback provided as parameter 1 is not a function. at :1:1

与传递匿名函数相比:

> requestAnimationFrame(() => { console.log('hi') })

hi

<小时/>

您需要传递一个函数,该函数将在 requestAnimationFrame 计时器到期时调用。

其中一个例子是:

// Vanilla Javascript
window.requestAnimationFrame(function() { drawball(a,b,c,x1,y1) } );

// ES6
window.requestAnimationFrame(() => { drawball(a,b,c,x1,y1) } );

在这些情况下,传递给 requestAnimationFrame 的参数是一个函数,它将被调用并执行 drawball 函数。

关于javascript - Canvas 动画(window.requestAnimationFrame),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47210622/

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