HTML 5 画布填充颜色

HTML 5 canvas fill color

本文关键字:填充 颜色 布填充 HTML      更新时间:2023-09-26

我在使用以下脚本时遇到问题

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))时,它不起作用。

任何人都可以让我知道这里有什么问题吗?

它适用于所有递增的值,但不适用于递减值。

检查 jsfiddle

我想

出了解决方法,现在工作正常。

我通过ctx.beginPath();实现了它