简体   繁体   中英

HTML 5 canvas fill color

I am having a problem with the following script

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
}

When i do loop(40) this works and then if i do loop(50) then also it works but when i want to give smaller value(like loop(20) ) than the current value it doesn't works.

Can anyone please let me know what is the problem here ?

it works for all increasing values but not for decreasing values.

Check on jsfiddle

I figured out the workaround and it works fine now.

I achieved it through ctx.beginPath();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM