25.02.2013 Views

Peter Lubbers - Pro HTML 5 Programming

Pro HTML 5 Programming

Pro HTML 5 Programming

SHOW MORE
SHOW LESS

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

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

Download from Wow! eBook <br />

62<br />

CHAPTER 2 ■ USING THE <strong>HTML</strong>5 CANVAS API<br />

Listing 2-28. The getColor function<br />

function getColor(intensity) {<br />

var colors = ["#072933", "#2E4045", "#8C593B", "#B2814E", "#FAC268", "#FAD237"];<br />

return colors[Math.floor(intensity/2)];<br />

}<br />

Whenever the mouse moves or hovers over an area of the canvas, a point is drawn. The point grows<br />

in size (and brightness) the longer the mouse stays in the immediate area. As shown in Listing 2-29, we<br />

use the context.arc function to draw a circle of a given radius, and we draw a brighter, hotter color for<br />

larger radius values by passing the radius to our getColor function.<br />

Listing 2-29. The drawPoint function<br />

function drawPoint(x, y, radius) {<br />

context.fillStyle = getColor(radius);<br />

radius = Math.sqrt(radius)*6;<br />

context.beginPath();<br />

context.arc(x, y, radius, 0, Math.PI*2, true)<br />

context.closePath();<br />

context.fill();<br />

}<br />

In the addToPoint function—which you will recall is accessed every time the mouse moves or hovers<br />

over a point—a heat value is increased and stored for that particular point on the canvas. Listing 2-30<br />

shows that the maximum point value is 10. Once the current value of heat for a given pixel is found, the<br />

appropriate pixel is passed to drawPoint with its corresponding heat/radius value.<br />

Listing 2-30. The addToPoint function<br />

function addToPoint(x, y) {<br />

x = Math.floor(x/SCALE);<br />

y = Math.floor(y/SCALE);<br />

if (!points[[x,y]]) {<br />

points[[x,y]] = 1;<br />

} else if (points[[x,y]]==10) {<br />

return<br />

} else {<br />

points[[x,y]]++;<br />

}<br />

drawPoint(x*SCALE,y*SCALE, points[[x,y]]);<br />

}<br />

Finally, the initial loadDemo function is registered to be called whenever the window completes<br />

loading.

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

Saved successfully!

Ooh no, something went wrong!