2011-05-25 99 views
0

在以下示例中,如何執行以下HTML帆布梯度動畫

  1. 當我創建在createGradient函數的梯度,僅第一弧具有多個顏色,第二弧具有單一顏色

  2. 當animate函數被調用時,我想只改變一個指定的梯度,而不是所有的人都

function init() { 
    can = document.getElementById("can"); 
    ctx = can.getContext("2d"); 
    drawGradients(); 
    var t=setTimeout("animate()",3000); 
} 

function drawGradients() { 
    var points = [[50,50,5, 50,50,50], [275,275,5, 275,275,50]]; 
    for (var i=0; i < points.length; i ++) { 
     var cords = points[i]; 
     createGradient (points[i]); 
    } 

}   

function createGradient(cds) { 
    var grad = ctx.createRadialGradient(cds[0],cds[1],cds[2],cds[3],cds[4],cds[5]); 
    grad.addColorStop(0, 'white'); 
    grad.addColorStop(1, 'black'); 
    ctx.fillStyle=grad; 
    ctx.arc(cds[3],cds[4], cds[5], 0, 2 * Math.PI); 
    ctx.fill(); 

} 

function animate() { 
    var cds =[50,50,5, 50,50,50]; 
     var grad = ctx.createRadialGradient(cds[0],cds[1],cds[2],cds[3],cds[4],cds[5]); 
     grad.addColorStop(0, 'white'); 
     grad.addColorStop(1, 'blue'); 
     ctx.fillStyle=grad; 
     ctx.arc(cds[3],cds[4], cds[5], 0, 2 * Math.PI); 
     ctx.fill(); 
    }   

</script> 

+1

很有可能完全無關的問題,但它通常是更好地做到'的setTimeout(動畫,3000)'不是'的setTimeout( 「動畫()」,3000)'因爲後者使用'eval'。 – icktoofay 2011-05-25 01:58:37

回答

1

你的第一個問題是,因爲它是重繪在第二次弧。這是因爲你從不關閉路徑。由於它們位於相同的路徑上,因此它們只會獲得一個漸變,所以看起來像一個形狀沒有漸變,但實際上它使用的是其他形狀的顏色!

要解決辦:

ctx.beginPath() 
ctx.arc(cds[3],cds[4], cds[5], 0, 2 * Math.PI); 
ctx.closePath() 
ctx.fill(); 

這也將解決您的有生問題,現在動畫只會改變梯度之一。

工作代碼:

http://jsfiddle.net/8AB3D/