Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
71
rated 0 times [  74] [ 3]  / answers: 1 / hits: 24387  / 14 Years ago, fri, july 23, 2010, 12:00:00

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


More From » html

 Answers
23

I've aded some code here: https://code.google.com/archive/p/canvasimagegradient/ that adds a drawImageGradient function to the CanvasRenderingContext2D. You can draw an image with a linear or radial gradient. It doesn't work in IE, even with excanvas, due to the lack of getImageData/putImageData support.


The following code for example will draw an image with a radial gradient (context retrieve and image load not shown):


var radGrad = ctx.createRadialGradient(
img.width / 2, img.height / 2, 10,
img.width / 2, img.height / 2, img.width/2);
radGrad.addColorStop(0, "transparent");
radGrad.addColorStop(1, "#000");

ctx.drawImageGradient(img, 112.5, 130, radGrad);

The code works as follows:



  1. Create a canvas element dynamically and draw the image on it.

  2. Retrieve the imageData for this new canvas.

  3. Retrieve the imageData for the location on the canvas you want to draw the image on to.

  4. Iterate through the destination imageData and update each pixel adding together a percentage (derived from the gradient transparency value) of the image and destination pixel values.

  5. Finally put the updated image data back onto the destination canvas.


Obviously performance is an issue as images get larger. The image on https://code.google.com/archive/p/canvasimagegradient/ it takes about 6-10ms to draw. A 1024x768 image takes about 100ms-250ms to draw. Still usable though as long as you're not animating.


[#96129] Wednesday, July 21, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
seth

Total Points: 307
Total Questions: 114
Total Answers: 96

Location: Kenya
Member since Mon, Jun 14, 2021
3 Years ago
;