Translate Transformation in Canvas: HTML5

Advertisement:

Transformation are the way objects are drawn on to the canvas. There are 3 transformations.
1. Translate
2. Scale
3. Rotate

..along with a way to define our own free-form transformations.

In this video tutorial, we shall see how to use Translate Transformation.

translate-transformation-canvas-html5

Translate Transformation moves the canvas origin to a new location.

index.html and myStyle.css file content are same as Linear Gradients in Canvas: HTML5

JavaScript file: Translate Transformation
myScript.js

1
2
3
4
5
		context.fillStyle = "red";
		context.fillRect(0, 0, 75, 75);
 
		context.translate(80, 80);
		context.fillRect(0, 0, 75, 75);

Here we draw a red color filled Rectangle at 0px x-axis and 0px y-axis, with a width and height of 75px each. Next we call translate method, and change the point of origin of the canvas to 80px x-axis and 80px y-axis. Then we copy paste the same rectangle code with same settings, but this time, the rectangle appears at the new canvas origin i.e., at 80px x-axis and 80px y-axis.

JavaScript file: Full Code
myScript.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
window.onload = canvas;
 
function canvas()
{
	var myCanvas = document.getElementById("myCanvas");
 
	if( myCanvas && myCanvas.getContext("2d") ) 
	{
		var context         = myCanvas.getContext("2d");
 
		context.shadowColor = "black";
		context.shadowBlur  = 20;
 
		context.fillStyle   = "red";
		context.fillRect(0, 0, 75, 75);
 
		context.translate(80, 80);
		context.fillRect(0, 0, 75, 75);		
 
		context.lineWidth   = 2;
		context.strokeStyle = "blue";
		context.arc(100, 100, 20, 0, 2 * Math.PI);
		context.fill();
		context.stroke();
	}
}

Here we apply shadow effect to 3 elements: 2 rectangles and 1 circle. When we draw circle with (100, 100) as its center, the origin is traced from (80, 80) and not (0, 0), as we draw the arc/circle after calling translate() method.

Translate Transformation in Canvas: HTML5


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=vSasdyo69bU [Watch the Video In Full Screen.]



Note: Since all the elements which follow translate method will have a new origin, we can effectively use canvas status and save, restore the status to our advantage.

Leave a Reply

Your email address will not be published. Required fields are marked *