Canvas- Draw Text with Linear and Radial Gradients

Written by @m_k_amin 26 June 2013

It's interesting to use gradient colors in text writings. HTML5 Canvas fill style can be more complex than a simple color and Linear Gradients or Radial Gradients can be used for it. Any possible color definitions in HTML can also be used here. You can also use alpha transparency value for the colors. The code below shows how HTML5 Canvas texts can be drawn with Radial and Linear gradients styles.

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-->
<canvas id="myCanvas" width="400" height="230"></canvas>
<script>
    var cnv = document.getElementById('myCanvas')
    var ctx = cnv.getContext('2d')
	var t1, w1, t2, w2
	
   	ctx.font= "bold 40pt serif"
	ctx.textBaseline= 'middle'
	t1= 'Linear-Gradient'
	w1 = ctx.measureText(t1).width
	t2= 'Radial-Gradient'
	w2= ctx.measureText(t2).width
	
    ctx.fillStyle= "gray"
	ctx.fillRect(0, 60, 400, 2)
	ctx.fillRect(0, 160, 400, 2)
	
    var LinGrad= ctx.createLinearGradient(2, 60, w1+2, 60)
	LinGrad.addColorStop(0, "rgba(1, 150, 225, 0.5)")
	LinGrad.addColorStop(0.33, "rgba(2, 30, 225, 0.9)")
	LinGrad.addColorStop(0.66, "rgba(78, 1, 225, 0.9)")	
	LinGrad.addColorStop(1, "rgba(155, 1, 225, 0.5)")
	
	var RadGrad= ctx.createRadialGradient(2+w1/2, 160, 1, 2+w1/2, 150, 180)
	RadGrad.addColorStop(0, "rgba(1, 150, 225, 0.5)")
	RadGrad.addColorStop(0.33, "rgba(2, 30, 225, 0.9)")
	RadGrad.addColorStop(0.66, "rgba(78, 1, 225, 0.9)")	
	RadGrad.addColorStop(1, "rgba(155, 1, 225, 0.5)")

	
	ctx.strokeStyle=LinGrad
    ctx.fillStyle= LinGrad
    ctx.strokeText(t1, 5, 60)    
    ctx.fillText(t1, 5, 60)

	ctx.strokeStyle=RadGrad
    ctx.fillStyle= RadGrad
    ctx.strokeText(t2, 5, 160)        
    ctx.fillText(t2, 5, 160)
</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
TRENDING POST
1
2
3
4
5
VISITORS
Online Users: 12
Recent Members:
advertisement 2