Canvas- Linear and Radial Gradients with Transparency

Written by @m_k_amin 13 June 2013

Filling objects with simple uniform colors are somehow boring. HTML5 Canvas provides two types of gradients, linear gradients and radial gradients, which let shapes and objects be filled more beautifully. You can add many colors in the gradient and also make some of them transparent. The linear gradient can be in any direction and it is not essential to be horizontal or vertical. In the case of radial gradient two circles are needed and the gradient comes between them. Note that it is not necessary to define the two circles concentric, and you can use any formats to define colors. This code shows how to deal with HTML5 Canvas Radial and Linear gradients and use them.

Code Snippet:

                                                
                                                <!-- this script is provided by www.html5freecode.com coded by: Kerixa Inc. -->
<!-- This Script is from www.html5freecode.com, Coded by: Kerixa Inc-->
<br>
<canvas id="myCanvas" width="400" height="230"></canvas>
<script>
    var cnv = document.getElementById('myCanvas')
    var ctx = cnv.getContext('2d')

    ctx.beginPath()
    ctx.moveTo(110, 110)
    ctx.lineTo(310, 110)
    ctx.lineWidth= 5
    ctx.stroke()   
    
    var LinGrad= ctx.createLinearGradient(20, 20, 170, 130)
	LinGrad.addColorStop(0, "yellow")
	LinGrad.addColorStop(0.4, "rgba(160, 250, 220, 0.3)")
	LinGrad.addColorStop(0.9, "rgba(30, 230, 250, 0.7)")
	LinGrad.addColorStop(1, "#00BBFF")
	
	var RadGrad= ctx.createRadialGradient(210, 120, 30, 210, 120, 100)
	RadGrad.addColorStop(0, "rgba(200, 80, 5, 0.9)")
	RadGrad.addColorStop(0.3, "rgba(250, 60, 10, 0.8)")
	RadGrad.addColorStop(0.7, "rgba(250, 170, 190, 0.7)")
	RadGrad.addColorStop(1, "rgb(255,255,255)")
	    
    ctx.fillStyle= RadGrad
    ctx.fillRect(110, 20, 200, 200) 

 	ctx.beginPath()
    ctx.lineWidth= 2
	ctx.strokeRect(20, 20, 150, 110)
    ctx.strokeStyle= "Brown"
    ctx.fillStyle= LinGrad
    ctx.fillRect(20, 20, 150, 110)    
    ctx.stroke()       
</script>
<div style="text-align: left"><font face="Tahoma"><br><a target="_blank" href="http://www.html5freecode.com"><span style="font-size: 8pt; text-decoration: none">HTML5 Free Code</span></a></font></div><a target='_blank' href='www.html5freecode.com' style='font-size: 8pt; text-decoration: none'>Html5 Free Codes</a>                                                
                                            

Example:


About @m_k_amin

This user is pending a biography.

M

Comments


Here you can leave us commments. Let us know what you think about this code tutorial!

0 / 300

TRENDING POST
1
2
3
4
5
VISITORS
Online Users: 12
Recent Members: FOTPU
advertisement 2