2013-12-13 105 views
1

問題是,動畫每幀都會創建一個三角形。但我想,只有一個三角形移動/動畫。我該如何解決? 當時畫布在隨機的X和Y位置上繪製一個三角形,然後向左移動,然後向右移動,依此類推。每幀畫布創建一個新的三角形,但我只想讓該畫布動畫一個三角形。如何用一個移動的三角形/矩形創建畫布動畫?

window.onload = function() { 

var canvas = document.getElementById('canvas'); 
var ctx = canvas.getContext('2d'); 
var W = canvas.width = window.innerWidth; 
var H = canvas.height = window.innerHeight; 

var x = Math.floor(Math.random()*W); 
var y = Math.floor(Math.random()*H); 

var speed = 20; 

function animate() { 

    reqAnimFrame = window.mozRequestAnimationFrame || 
       window.webkitRequestAnimationFrame || 
       window.msRequestAnimationFrame  || 
       window.oRequestAnimationFrame 
       ; 

    reqAnimFrame(animate); 

    x += speed; 

    if(x <= 0 || x >= W - 300){ 
     speed = -speed; 
    } 

    draw(); 
} 

function draw() { 
    ctx.beginPath(); 
    ctx.fillStyle = "rgba(0,204,142,0.5)"; 
    ctx.moveTo(x,y); 
    ctx.lineTo(x + 150, y + (-180)); 
    ctx.lineTo(x + 300, y); 
    ctx.scale(1,1); 
    ctx.rotate(Math.PI/1); 
    ctx.fill(); 
} 
animate(); 

};//onload function 

回答

2

您需要清除畫布的每一幀,以及:

function draw() { 
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); 
    ctx.beginPath(); 
    ctx.fillStyle = "rgba(0,204,142,0.5)"; 
    ctx.moveTo(x,y); 
    ctx.lineTo(x + 150, y + (-180)); 
    ctx.lineTo(x + 300, y); 
    ctx.scale(1,1); 
    ctx.rotate(Math.PI/1); 
    ctx.fill(); 
} 

PS:你並不需要你的動畫循環內部填充工具,它只會吃不必要的週期。把它放在腳本的開頭,你會很好,而且你也缺少前綴版本:

reqAnimFrame = window.requestAnimationFrame || /// you will need this too.. 
       window.mozRequestAnimationFrame || 
       window.webkitRequestAnimationFrame || 
       window.msRequestAnimationFrame  || 
       window.oRequestAnimationFrame 
       ; 
+0

那一個很難! :-) – GameAlchemist

+2

@GameAlchemist對於新來的人不知道它肯定會.. ..隨時upvote :) – K3N