渐变映射作为HTML5画布元素中的不透明度?

时间:2016-10-05 21:02:38

标签: javascript html5 html5-canvas

有没有办法在canvas元素上创建不透明度贴图 我试图淡化生成的图像,如下所示。

实施例: enter image description here

1 个答案:

答案 0 :(得分:2)

我不相信有任何方法可以直接使用渐变蒙版绘制图像,但您可以将图像预先绘制到单独的画布上,并使用globalCompositeOperation绘制蒙版线性渐变,然后使用drawImage将该画布绘制到主画布上。

工作示例:



var cvs = document.getElementById('cvs');
var ctx = cvs.getContext('2d');

// Draw some background colors.
ctx.fillStyle = "#FF6666";
ctx.fillRect(0, 0, 150, 200);
ctx.fillStyle = "#6666FF";
ctx.fillRect(150, 0, 150, 200);

// Load the image.
img = new Image();
img.onload = function() {
    // Create a canvas in memory and draw the image to it.
    var icvs = document.createElement('canvas');
    icvs.width = img.width;
    icvs.height = img.height;
    var ictx = icvs.getContext('2d');
    ictx.drawImage(img, 0, 0);

    // For masking.
    ictx.globalCompositeOperation = 'destination-out';

    // Draw the masking gradient.
    var gradient = ictx.createLinearGradient(0, 0, 0, icvs.height);
    gradient.addColorStop(0, "transparent");
    gradient.addColorStop(1, "white");
    ictx.fillStyle = gradient;
    ictx.fillRect(0, 0, icvs.width, icvs.height);

    // Draw the separate canvas to the main canvas.
    ctx.drawImage(icvs, 25, 25, 250, 150);
};
img.src = '//i.stack.imgur.com/dR8i9.jpg';

<canvas id="cvs" width="300" height="200"></canvas>
&#13;
&#13;
&#13;