gpt4 book ai didi

javascript - requestAnimationFrame 太快

转载 作者:行者123 更新时间:2023-11-29 21:05:48 26 4
gpt4 key购买 nike

我正在 Canvas 中创建简单的动画。我使用 requestanimationframe 来控制动画。有3圈。但我只能看到 3 个圆圈,而且动画太快了。我的问题是如何减慢动画速度以及如何显示每一帧。这是我的直播 link .

const swing = (time) => {
for(var i = 0; i < 3; i++) {
circle[i] = new ball();
circle[i].draw(i, circle[i].color);
}

requestAnimationFrame(swing);
}

requestAnimationFrame(swing);
//swing();


function ball(i){
this.x = random(100, 150);
this.y = random(40, 60);
this.radius = 45;
this.color = getRandomColor(random(1, 30));
this.strokeText = "m"

ctx.clearRect(0, 0, el.width, el.height);
this.draw = function(i, color){
ctx.beginPath();
ctx.font="30px Verdana";
ctx.arc(i*this.x, this.y, this.radius, 0, 2*Math.PI, false);
ctx.fillStyle = color;
ctx.globalAlpha = 0.5;
ctx.strokeText(i,i*this.x,this.y);
ctx.fill();
ctx.closePath();
}
}

提前致谢。

编辑:- 我正在创建类似这样的东西:- http://codepen.io/jscottsmith/pen/oWyxjp?editors=1010

最佳答案

举个简单的例子,让三个球做圆周运动:

// refer below 
// http://codepen.io/jscottsmith/pen/oWyxjp?editors=1010
const el = document.getElementById('canvas'),
ctx = el.getContext('2d');
let circle = [];
el.width = document.body.clientWidth;
el.height = document.body.clientHeight;

const getRandomColor = (i) => {
let count = 30,
color = 1,
hue = (i / count * color) * 360;
return `hsla(${hue}, 100%, 50%, 1)`
}

for (var i = 0; i < 3; i++) {
circle[i] = new ball();
}

let angle = 0;
let speed = 0.02;

const swing = (time) => {
ctx.clearRect(0, 0, el.width, el.height);

for (var i = 0; i < 3; i++) {
circle[i].x = circle[i].x + Math.cos(angle) * 1;
circle[i].y = circle[i].y + Math.sin(angle) * 2;
}
for (var i = 0; i < 3; i++) {
circle[i].draw(i, circle[i].color);
}
angle += speed;
requestAnimationFrame(swing);
}

requestAnimationFrame(swing);
//swing();


function ball(i){
this.x = random(100, 150);
this.y = random(40, 60);
this.radius = 45;
this.color = getRandomColor(random(1, 30));
this.strokeText = "m"

this.draw = function(i, color){
ctx.beginPath();
ctx.font="30px Verdana";
ctx.arc(i*this.x, this.y, this.radius, 0, 2*Math.PI, false);
ctx.fillStyle = color;
ctx.globalAlpha = 0.5;
ctx.strokeText(i,i*this.x,this.y);
ctx.fill();
ctx.closePath();
}
}

function random (num1, num2) {
var max = Math.max(num1, num2);
var min = Math.min(num1, num2);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
#canvas {
width: 600px;
height: 600px;
}
<canvas id="canvas"></canvas>

关于javascript - requestAnimationFrame 太快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44173347/

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