2013-10-25 154 views
1

我有以下腳本HTML 5個畫布的填充顏色

var ctx = demo.getContext('2d'), 
    w = demo.width, 
    h = demo.height, 
    img = new Image, 
    url = 'http://i.imgur.com/1xweuKj.png', 
    grd = ctx.createLinearGradient(0, 0, 0, h); 

grd.addColorStop(0, 'rgb(0, 130, 230)'); 
grd.addColorStop(1, 'rgb(0, 20, 100)'); 

img.onload = loop; 
img.crossOrigin = 'anonymous'; 
img.src = url; 

function loop(x) { 
    /// since we will change composite mode and clip: 
    ctx.save(); 

    /// clear background with black 
    ctx.fillStyle = '#000'; 
    ctx.fillRect(0, 0, w, h); 

    /// remove waveform, change composite mode 
    ctx.globalCompositeOperation = 'destination-atop'; 
    ctx.drawImage(img, 0, 0, w, h); 

    /// fill new alpha, same mode, different region. 
    /// as this will remove anything else we need to clip it 
    ctx.fillStyle = grd; 
    ctx.rect(0, 0, x, h); 
    ctx.clip(); /// et clipping 
    ctx.fill(); /// use the same rect to fill 

    /// remove clip and use default composite mode 
    ctx.restore(); 

    /// loop until end 
} 

當我做loop(40)這個作品,然後,如果我做loop(50)那麼也它的工作原理,但一個問題,當我想給較小的值(如loop(20))比當前值不起作用。

任何人都可以讓我知道這裏有什麼問題嗎?

它適用於所有遞增值,但不適用於遞減值。

Check on jsfiddle

+0

工作正常,即使小的值 – ViliusL

+0

它的工作原理,但不是在同一時間。假設你做了循環(60),然後做循環(20),它會顯示循環(60)值。我通過'ctx.beginPath();'修復了它 –

回答

2

我想出解決辦法,現在工作得很好。

我實現它通過ctx.beginPath();