2013-10-25 151 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();