Reputation: 55
I'm new to canvas.js.please help me to this to slow the box movement. I would like to try the box to move according to x-axis and y-axis array values.It is working but too speed.I need to reduce speed and want to scale the axis.can we do like that??please help me.
<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);
}
Upvotes: 0
Views: 584
Reputation: 138557
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();
this loops trough the xval array,moves with a speed of xval pixels/0.1s and goes to the next xval after 1 second. Your mistake:
for(var i=0;i<xval.length;i++){ rect1.x+=xval[i]; rect1.y+=yval[i]; }
This adds up all your xval values (rect=rect+1+2+3+4+5) to the position, so your rect has a speed of 15px, and is moved as fast as possible (requestAnimation frame).This is not what you wanted...
By the way your usage of requestAnimation frame is wrong (setInterval(requestAnimationFrame,1000) is nonsense). It calls the passed function when there is free rendering time:
function draw(){
draw();
} //runs very fast, but may overload the computer
function draw(){
requestAnimationFrame(draw);
}//runs as fast as the computer can
But using requestAnimation frame in your case makes no sense. Use it when rendering some 3D stuff or sth similarily heavy...
Upvotes: 1