Canvas- Clipping, Effective Way for Drawing and Filling

Written by @m_k_amin 18 June 2013

HTML5 Canvas has effective feature for using the specific region of the context as the usable area, called Clipping. The benefit is that it can be used as a way for drawing or filling a defined part of an object or text, not its whole; so it is not important where and what you draw, the part that is inside the clipping region is shown. In the code below we have used HTML5 Canvas Clipping feature for filling part of a text and part of a triangle. Note that, for having more than one clipping region, you can save the current state of the context before call clip function and then restore it again. And be aware that we have made the clipping region visible for showing what has been done, but you can hide it if it isn't necessary to have more beautiful 2D graphics.

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="250"></canvas>
<script>
    var cnv = document.getElementById('myCanvas')
    var ctx = cnv.getContext('2d')

	ctx.strokeStyle= 'lightblue'
	ctx.strokeRect(30, 10, 140, 45);
	ctx.rect(30, 10, 140, 45)
	ctx.font= "40pt Arial"
	ctx.strokeStyle= 'darkgreen'	
    ctx.strokeText('Clipping', 18, 70)	
	ctx.fillStyle= 'magenta'
	ctx.save()
	ctx.clip()
    ctx.fillText('Clipping', 18, 70)
    
    ctx.restore()
	ctx.beginPath()
	ctx.moveTo(20, 100)
	ctx.lineTo(20, 200)
	ctx.lineTo(200, 200)
	ctx.lineTo(20, 100)
	
	ctx.moveTo(40, 140)
	ctx.lineTo(75, 140)
	ctx.lineTo(75, 180)
	ctx.lineTo(40, 180)	
	ctx.lineTo(40, 140)	
    ctx.strokeStyle= "lightblue"
    ctx.stroke()
	ctx.clip()
	
	ctx.beginPath()
	ctx.moveTo(60, 80)
	ctx.lineTo(0, 190)
	ctx.lineTo(100, 190)
	ctx.closePath()
	ctx.fill()
</script>
<div style="text-align: left"><font face="Tahoma"><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