簡體   English   中英

畫布中的動畫有多慢

[英]how slow the animation in canvas

我是新來canvas.js.please幫我這個慢箱中移動。 我想嘗試根據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);

}
 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 pixel / 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幀)。你想要什么...

順便說一句,您對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東西或類似地較重時使用它...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM