Is it possible to make a gradient-transparent/layer masking image using canvas?

后端 未结 5 1901
傲寒
傲寒 2021-02-05 14:01

I\'ve been following the lessons about transparency and gradients on the Mozilla site: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Applying_styles_an

5条回答
  •  生来不讨喜
    2021-02-05 14:37

    To correctly merge two images using a transparency mask it's first necessary to take one of the two images and put it into an off screen canvas, and add the desired transparency mask using context.globalCompositeOperation = destination-out per @Tommyka's answer

    var offscreen = document.createElement('canvas'); // detached from DOM
    var context = offscreen.getContext('2d');
    context.drawImage(image1, 0, 0, image1.width, image1.height);
    
    var gradient = context.createLinearGradient(0, 0, 0, img.height);
    gradient.addColorStop(0, "rgba(255, 255, 255, 0.5)");
    gradient.addColorStop(1, "rgba(255, 255, 255, 1.0)");
    context.globalCompositeOperation = "destination-out";
    context.fillStyle = gradient;
    context.fillRect(0, 0, image1.width, image1.height);
    

    Then, to actually merge the two images you then need to draw the other image into another canvas, and then simply draw the alpha-composited offscreen canvas on top of that:

    var onscreen = document.getElementById('mycanvas');
    var context2 = onscreen.getContext('2d');
    context2.drawImage(image2, 0, 0, image2.width, image2.height);
    context2.drawImage(offscreen, 0, 0, onscreen.width, onscreen.height);
    

    Demo at http://jsfiddle.net/alnitak/rfdjoh31/4/

提交回复
热议问题