Just thought I should share this tip with you, Now that I have been playing around with Canvas Object in HTML5 for a while I think more tips like these will flow as they used to in past. I’ve been working on a jQuery plugin that will offer something cool, stay tuned for that. This post technique is backbone to that plugin.
Anyway lets get back to the point without wasting more time.
Problem
Canvas Gradient transparency that could be used as Mask
Step 1
Lets get our Canvas read and draw an Image on it
Markup
1 2 3 4 5 |
<canvas id="mycanvas" width="600" height="600"> Your browser does not support HTML5 Canvas. Try downloading latest Chrome, Firefox, Safari, Opera or Internet explorer. </canvas> |
Draw Image
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
var mycanvas = document.getElementById("mycanvas"); var context = null; var x,y = 0; if(mycanvas && mycanvas.getContext) { context = mycanvas.getContext("2d"); // background context.fillStyle = "#fff"; context.fillRect(0,0,600,600); var img = new Image(); img.src = "puzzle.png"; img.onload = function() { context.drawImage(img,0,0); // CODE SNIPPET 2 } |
By now you would have something like this
Let now add our transparent gradient to out canvas object.
Here is the code for that
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// start path to create a rectangle context.beginPath(); // put stroke color to transparent context.strokeStyle = "transparent" // draw rectablge towards right hand side context.rect(400,0,200,800); // create linear gradient var grdLinear = context.createLinearGradient(400, 0, 600, 0); // Important bit here is to use rgba() grdLinear.addColorStop(0, "rgba(247, 247, 247, 0)"); grdLinear.addColorStop(0.25, "rgba(247, 247, 247, 0.4)"); grdLinear.addColorStop(0.5, "rgba(247, 247, 247, 0.6)"); grdLinear.addColorStop(0.75, "rgba(247, 247, 247, 0.8)"); grdLinear.addColorStop(1, 'rgba(247, 247, 247, 1)'); // add gradient to rectangle context.fillStyle = grdLinear; // step below are pretty much standard to finish drawing an object to canvas context.fill(); context.stroke(); context.closePath(); |
Above code should go under where it says CODE SNIPPET 2 in first snippet.
Here is the result
You can play around with the colours, I’ve created a Pen at code pen so that you can mess around and find a suitable setting.
You can introduce transparency on both or all 4 sides of above image. You can give it a try.
I hope this helps,
Cheers,
Great, Thanks for letting me know
This is not transpaency – you are simply adding a white gradient in the most complicated useless way possible.