Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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_and_colors but I have not been able to figure this one out.

I know I can achieve these effects with a png image; however, in the program I am working on the gradient will change constantly according to where the image is moved.

Here's an example of the effect I'm looking for. http://home.insightbb.com/~epyonxl1/gradientex.jpg

like image 511
mjrevel Avatar asked Jul 23 '10 16:07

mjrevel


2 Answers

Its possible to use context.globalCompositeOperation to make the the mask

context.drawImage(img, 0, 0, img.width, img.height, 0,0, img.width, img.height);
context.globalCompositeOperation = "destination-out";
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.fillStyle = gradient;
context.fillRect(0, 0, img.width, img.height);

This do not do per pixel manipulation and should be faster

like image 67
Tommyka Avatar answered Oct 13 '22 01:10

Tommyka


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/

like image 30
Alnitak Avatar answered Oct 12 '22 23:10

Alnitak