gpt4 book ai didi

javascript - 圆形动画运行一段时间后速度加快

转载 作者:行者123 更新时间:2023-11-27 23:10:21 26 4
gpt4 key购买 nike

我希望你能帮助我,因为我遇到了我的宿敌……数学!

我正在制作一个会不断运行的背景动画,它工作得很好,除了一件小事,它在很长一段时间内会加速一点点。

我已经提取了该脚本必需的代码。

动画很简单,它创建了一堆圆圈,然后永远以圆周运动移动。创建时随机更快/更慢和更大/更小。

因此,如果动画运行时间为 40 分钟~圆形动画将大大提高其速度!

构造函数运行大约100次,实例被放入粒子数组中,这里我只是在实例化圆时设置默认值

constructor(){
this.radius = 100;
this.xPos = Math.round(Math.random() * canvas.width);
this.yPos = Math.round(Math.random() * canvas.height);
this.counter = 0;
this.maxWidth = 14;
this.width = Math.floor(Math.random() * (this.maxWidth - 4) + 4); //4 -> 24
this.speed = Math.random() * 0.4; //0.0 -> 0.4
this.color = "#3cccd3";
this.alpha = this.getAlpha();

this.sign = Math.round(Math.random()) * 2 - 1;
}

绘制方法在动画循环中运行,我检查了许多有关圆形运动动画的示例,这似乎是流行的方法,但动画并不像我的那样加速:)

draw() {
this.counter += this.sign * this.speed;

ctx.beginPath();
//define the circleparticle
ctx.arc(this.xPos + this.radius * Math.cos(this.counter / 100) ,
this.yPos + this.radius * Math.sin(this.counter / 100) ,
this.width,
0,
Math.PI * 2,
true);


ctx.globalAlpha = this.alpha;
ctx.fillStyle = this.color;
ctx.fill();
}

这只是循环

function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height); //empty the canvas
particles.forEach((particle) => particle.draw()); //run the draw method

if(playParticles && !gameFocus) {
requestAnimationFrame(draw); //rerun
}
}

更新这里是修复

在构造函数中

this.speed = 100 + Math.random() * 500;

在draw方法中

this.timestamp = Math.floor(Date.now());
this.counter = this.sign * (this.timestamp / this.speed * Math.PI);

最佳答案

我在您的代码中找不到任何内容来解释旋转速度的持续增加。

但是,动画的速度是调用绘制方法的频率的乘积。您可以为每次调用将计数器增加固定数量,但不能保证它会以任何给定频率被调用。

requestAnimationFrame 将在每次准备好进行新渲染时调用您的绘制函数。其时间可能会因多种因素而异,例如每次绘制所需的时间、网页的总计算负载、设备的总 CPU 负载或其电源设置。

不要让计数器成为绘制方法调用计数的乘积,而是考虑将其设为时间的乘积。因此,requestAnimationFrame 回调的第一个参数是一个时间戳,应用作该渲染每个部分的当前时间。

编辑:示例代码

下面的代码是一个简化的示例,生成 x 和 y,它们一起描述每秒一转的圆周运动。

requestAnimationFrame(
function(timestamp) {
var counter = timestamp / 1000 * Math.PI;
var x = Math.cos(counter);
var y = Math.sin(counter);
// do something with x and y
}
);

关于javascript - 圆形动画运行一段时间后速度加快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36235387/

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