Canvas- Coordinate System Transformation, Scaling and Shearing the Context

Written by @m_k_amin 16 June 2013

One way to design a proper shape is to create it in the usual coordinate system and then manipulate the coordinates. HTML5 Canvas lets you transform (translate) the coordinate system to a new place; it is also possible to rotate, scale (make bidder or smaller) and shearing the coordinate system. Html5 Canvas also has an option for defining a custom matrix to do all these things at the same time. Below we have shown these features by five examples.

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

	for (i=0; i<=4; i++){
		newCor(i)
		ctx.beginPath()
		var r=30
		ctx.arc(r+10, r+10, r, 0, 270*deg, false)
		ctx.lineTo(r+10,r+10)
		ctx.lineTo(2*r+10,r+10)
		ctx.moveTo(r+10,r+10)
		ctx.lineTo(r+10- r*Math.cos(45*deg),r+10+ r*Math.sin(45*deg))
	    ctx.lineWidth= 2
	    ctx.fillStyle= "lightblue"
	    ctx.strokeStyle= "darkblue"
	    ctx.fill()
	    ctx.stroke()
	}
    
    
function newCor(i){
    ctx.font= "16pt serif"
	ctx.fillStyle= "brown"
	switch (i){
		case 0:
		    ctx.fillText('Normal', 10, 100)
			break;
		case 1:
			ctx.scale(1.2, 1.2)
			ctx.translate(2*r+10, -5)
   		    ctx.fillText('Scale 1.2', 10, 100)			
			break;
		case 2:
			ctx.scale(1/1.3, 1/1.3)	//Undo Cas1
			
			ctx.rotate(45*deg)
			ctx.translate(135, -150)
		    ctx.fillText("Rotate 45'", 10, 100)
		    break;
		case 3:
			ctx.rotate(-45*deg)		//Undo Case2
			ctx.translate(-290,150)	//Undo Case2
			
			ctx.transform(1, 0.3, 0.3, 1, 0, 0)
		    ctx.fillText("Shear 0.3", 0, 100)
		    break;
		case 4:
			ctx.transform(1, -0.3, -0.3, 1, 0, 0)	//Undo Case 3
			var x= 45*deg
			ctx.transform(1.3*Math.cos(x), 0.3*Math.sin(x),-1.3*Math.sin(x), 2.3*Math.cos(x),250, 0)
		    ctx.fillText("Custom Matrix", 60, 30)
		    break;		    
	}
}
</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

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