我是canvas.js.please的新手,帮我this减慢盒子的移动速度。 我想尝试根据x轴和y轴数组值移动框。它工作但速度太快。我需要降低速度并想要缩放轴。我们喜欢那样吗?请帮帮我
<canvas width="2500" height="1500"></canvas>
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
var canvas = document.getElementsByTagName("canvas")[0]; //get the canvas dom object
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
// define a rect using a javascript object
var rect1={
x:20,
y:20,
width:40,
height:40,
}
var xval=[1,2,3,4,5];
var yval=[1,2,3,4,5];
// start the animation loop
requestAnimationFrame(animate);
//setInterval(requestAnimationFrame, 100);
function animate(time){
for(var i=0;i<xval.length;i++){
rect1.x+=xval[i];
rect1.y+=yval[i];
}
// draw the rects in their new positions
//setInterval(draw, 1000);
draw();
// request another frame in the animation loop
requestAnimationFrame(animate);
}
function draw(){
ctx.clearRect(0,0,cw,ch);
var r=rect1;
ctx.strokeRect(r.x,r.y,r.width,r.height);
}
答案 0 :(得分:0)
var current;
function animate(i=0){
clearInterval(current);
current=setInterval(move(i),100);//moves with 0.1 seconds per frame
if(i<xval.length-1){
setTimeout(animate(i+1),1000);//next speed in 1 second
}
}
function move(i){
scale=1;//change to your needs
rect1.x+=xval[i]×scale;//xval[i] is a speed
rect1.y+=yval[i]×scale;
draw();
}
//start
animate();
这循环通过xval数组,以xval像素/ 0.1s的速度移动,并在1秒后转到下一个xval。 你的错误:
for(var i=0;i<xval.length;i++){ rect1.x+=xval[i]; rect1.y+=yval[i]; }
这会将所有xval值(rect = rect + 1 + 2 + 3 + 4 + 5)加到该位置,因此你的rect的速度为15px,并尽可能快地移动(requestAnimation frame)。这不是你想要的......
顺便说一句,您对requestAnimation框架的使用是错误的(setInterval(requestAnimationFrame,1000)是无意义的)。它在有空闲渲染时间时调用传递的函数:
function draw(){
draw();
} //runs very fast, but may overload the computer
function draw(){
requestAnimationFrame(draw);
}//runs as fast as the computer can
但在你的情况下使用requestAnimation框架毫无意义。在渲染一些3D东西或者类似的东西时使用它......