简体   繁体   中英

Gradient map as opacity in a HTML5 canvas element?

Is there a way to create an opacity map on a canvas element I am trying to fade a generated image as shown below.

EXAMPLE: 在此处输入图片说明

I don't believe there is any way to directly draw an image with a gradiant mask, but you could pre-draw the image to a separate canvas, and use globalCompositeOperation to draw a masking linear gradient, then draw that canvas using drawImage to the main canvas.

Working Example:

 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> 

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