Html5 Canvas Gradients
Just like in CSS, you can create gradients in html5 canvas, too. If you couldn’t, I wouldn’t be that impressed with it. It would definitely be a feature that would be requested. Even though flat is in right now, everyone likes the ability to created the added touch of a slight gradient. However, just like in CSS, gradients can be a little tough to master, but with this tutorial, I’ll break down how html5 canvas gradients.
Gradients can be used to fill most shapes, such as rectangles, circles, lines, text, etc. Shapes on the canvas are not limited to solid colors (thank goodness). I really think it is interesting that you can apply gradients to lines, considering it took forever to get that feature added to Adobe Illustrator, and it’s an advanced vector program. Just like in Photoshop or Illustrator, there are 2 different types of gradients.
createLinearGradient(x,y,x1,y1) – Creates a linear gradient
createRadialGradient(x,y,r,x1,y1,r1) – Creates a radial gradient
Create Your Shape: Then add color stops
The addColorStop() method specifies the color stops, and its position on the gradient. Gradient positions can be anything from 0 to 1.
To use the gradient, you have to use the fillStyle or strokeStyle property with the gradient, and then draw the shape, like a rectangle, circle, text, or line.
Html5 Canvas Gradients: Linear
Create a linear gradient. Fill the rectangle with the gradient:
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;"> Your browser does not support the HTML5 canvas tag.</canvas> <script> var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); // Create gradient var grd=ctx.createLinearGradient(0,0,200,0); grd.addColorStop(0,"green"); grd.addColorStop(1,"blue"); // Fill with gradient ctx.fillStyle=grd; ctx.fillRect(10,10,150,80); </script>
Html5 Canvas Gradients: Radial
Create a radial/circular gradient. Fill rectangle with the gradient:
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;"> Your browser does not support the HTML5 canvas tag.</canvas> <script> var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); // Create gradient var grd=ctx.createRadialGradient(75,50,5,90,60,100); grd.addColorStop(.0,"green"); grd.addColorStop(1,"blue"); // Fill with gradient ctx.fillStyle=grd; ctx.fillRect(10,10,150,80); </script>
Changing the value of the green color stop from 0 to .5 makes the transition more harsh.
Html5 Canvas Gradients: Conslusion
Were you able to successfully create html5 canvas gradients? If you have any questions, or anything you’d like to add, feel free to leave your thoughts in the comments section below.