a blog for those who code

Monday, 19 October 2015

2D Transformations using Canvas element in HTML5

In this post we will be discussing about basics of 2D transformations using <canvas> element in HTML5. This will be helpful if you want to draw shapes at given positions with different orientations and sizes. In our previous post we have discussed about basics of <canvas> element. In this post we will take use of those methods and functions and continue our study about <canvas> element.


Now we will learn some basic methods for doing 2D transformations :

translate(x, y) - It remaps the (0,0) position on the canvas with values x and y.

scale(scalewidth, scaleheight) - It scales the current drawing either bigger or smaller based on scalewidth and scaleheight.

rotate(angle) - It rotates the current drawing based on the angle provided.


Note : By the above code you have modified the coordinates of the current context. So now if you draw anything using the same context, all drawings will be in that modified coordinate system i.e. all drawings will be scaled and rotated.

Save and Restore the Context

You can either save or restore your context based on your requirements. All properties which affect your drawing can be saved using the save() method and you can restore context using the restore() method. One thing to note that contexts are saved in Stack Format ( Last In First Out ), that means the last context which has been saved will be restored by the next restore() call. So it is always good to call restore() for every save operation.

Why Save and Restore is Helpful ?

Saving and Restoring the context will be helpful when you want to draw some shapes at a given position, with a given color etc., and do not want to affect other functions that uses the same context. So lets say you wanted to do some changes using the context object, you do that inside a function where first line will be context.save() and last line will be context.restore().

Drawing Text using Canvas

There are two main methods fillText() and strokeText() for drawing text and have a property font to specify the font style. For example :

context.font = "20px Arial";
context.fillText("Codingdefined.com", 10, 10); 
context.strokeText("Codingdefined.com", 10, 10); 

Check at : http://codepen.io/codingdefined/pen/Vvrogo

Please Like and Share the CodingDefined Blog, if you find it interesting and helpful.

No comments:

Post a Comment

Contact Us

Name

Email *

Message *

Sponsers

Best Hosting Plans

CC License