Working with Canvas
 

The Canvas element can be transformed. As an example, a text is written on the canvas at the coordinates (10, 30). 

ctx.font=“bold 22px Tahoma”;
ctx.textAlign=“start”;
ctx.fillText(“start”, 10, 30);

 

Result: 

Holla Tech - Learn HTML5

The translate(x,y) method is used to move the Canvas.
x indicates how far to move the grid horizontally, and y indicates how far to move the grid vertically.

ctx.translate(100, 150);

ctx.fillText(“after translate”, 10, 30);

 

In this example, the canvas is moved 100px to the right, and 150px down.
Result:

Holla Tech - Learn HTML5

Note!
Canvas has several methods for drawing paths, boxes, circles, text, and adding images.

The rotate() Method
 

The rotate() method is used to rotate the HTML5 Canvas. The value must be in radians, not degrees.

Here is an example that draws the same rectangle before and after rotation is set:

<

p dir=”ltr”>

ctx.fillStyle = “#FF0000”;
ctx.fillRect(10,10, 100, 100);

ctx.rotate( (Math.PI / 180) * 25);  //rotate 25 degrees.

ctx.fillStyle = “#0000FF”;
ctx.fillRect(10,10, 100, 100);

 

Holla Tech - Learn HTML5

Note!
The rotation will only affect drawings made after the rotation is done.

The scale() Method
 

The scale() method scales the current drawing. It takes two parameters:
– The number of times by which the image should be scaled in the X-direction.
– The number of times by which the image should be scaled in the Y-direction.

var canvas = document.getElementById(‘canvas1’);
ctx =canvas.getContext(‘2d’);
ctx.font=“bold 22px Tahoma”;
ctx.textAlign=“start”;
ctx.fillText(“start”, 10, 30);
ctx.translate(100, 150);
ctx.fillText(“after translate”, 0, 0);
ctx.rotate(1);
ctx.fillText(“after rotate”, 0, 0);
ctx.scale(1.5, 4);
ctx.fillText(“after scale”, 0,20);

 

 

This will scale the canvas 1.5 times in the X-direction, and 4 times in Y-direction:

Holla Tech - Learn HTML5

If you scale a drawing, all future drawings will also be scaled.


BACK NEXT

HTML MAIN COURSE PAGE

 

CONTACT HOLLA TECH LEARN SUPPORT