2016-11-27 68 views
0

我是canvas.js.please的新手,幫我減少框的移動速度。 我想嘗試框根據x軸和y軸陣列values.It運行,但速度太快。我需要降低速度,並希望縮放軸。我們這樣做??請幫助我。畫布中動畫的速度有多慢

<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
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)的位置,所以你的矩形具有15像素的速度,以及被移動爲(請求動畫幀)。這不是你想要的...

順便說一句,你使用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的東西或類似的重...

+0

謝謝@jonas w .i試過https://jsfiddle.net/6yah8dth/41/ here.its不working.pls幫我 – dhanu