In the previous post we discussed about canvas <a href=”http://learnhtml5.info/2011/10/translating-a-canvas-feature/ “>translation</a> method and now in this post we will discuss about another transformation method rotate. Using rotate method we can rotate the canvas element around the origin .
Rotate
This method takes angle as the parameter and the canvas element is rotated about this angle .This is shown in the figure below.
The rotation point is the origin of the canvas . Inorder to change the center point ,we have to use the translate
method.
A rotate example
In the below example we can use the rotate method to draw shapes around a circular pattern .We can also calculate the individual x and y co-ordinate . When we calculate co-ordinates we can alter the center position of the circle but not the circle themselves
We use two loops here the 1st one is used to specify the number of rings and the second one is used to determine the dots that has to be drawn in each pixel. Before drawing each circle the states are saved and the canvas co-ordinates are rotated by an angle that is specified by the total number of dots in the rings .The inner circle has 6 dots and in each and every step the angle is rotated by 360/6=60 degrees .With each new ring the total number of dots in the circle is doubled and the angle turn is reduced to half
<pre>function draw() { var ctx = document.getElementById('canvas').getContext('2d'); ctx.translate(75,75); for (var i=1;i<6;i++){ // Loop through rings (from inside to out) ctx.save(); ctx.fillStyle = 'rgb('+(51*i)+','+(255-51*i)+',255)'; for (var j=0;j<i*6;j++){ // draw individual dots ctx.rotate(Math.PI*2/(i*6)); ctx.beginPath(); ctx.arc(0,i*12.5,5,0,Math.PI*2,true); ctx.fill(); } ctx.restore(); } }</pre>