04.11.2015 Views

javascript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 21: Upcoming API s<br />

Transformations can be as simple or as complex as necessary. For example, it may be easier to draw the<br />

hands on the clock in the previous example by translating the origin to the center of the clock and then<br />

drawing the hands from there. Consider the following:<br />

var drawing = document.getElementById(“drawing”);<br />

//make sure < canvas > is completely supported<br />

if (drawing.getContext){<br />

var context = drawing.getContext(“2d”);<br />

//start the path<br />

context.beginPath();<br />

//draw outer circle<br />

context.arc(100, 100, 99, 0, 2 * Math.PI, false);<br />

//draw inner circle<br />

context.moveTo(194, 100);<br />

context.arc(100, 100, 94, 0, 2 * Math.PI, false);<br />

//translate to center<br />

context.translate(100, 100);<br />

//draw hour hand<br />

context.moveTo(0,0);<br />

context.lineTo(0, -85);<br />

//draw minute hand<br />

context.moveTo(0, 0);<br />

context.lineTo(-65, 0);<br />

}<br />

//stroke the path<br />

context.stroke();<br />

After translating the origin to (100,100), the center of the clock face, it ’ s just a matter of simple math to<br />

draw the lines in the same direction. All math is now based on (0,0) instead of (100,100). You can go<br />

further, moving the hands of the clock by using the rotate() method as shown here:<br />

var drawing = document.getElementById(“drawing”);<br />

//make sure < canvas > is completely supported<br />

if (drawing.getContext){<br />

var context = drawing.getContext(“2d”);<br />

//start the path<br />

context.beginPath();<br />

//draw outer circle<br />

(continued)<br />

689

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!