HTML5 Guidelines for Web Developers

(coco) #1
5.5 Paths 125

var deg2rad = function(deg) {
return deg*(Math.PI/180.0);
};


Talking of helper functions, let’s use two more to facilitate drawing circles and
sectors. For circles, we really only need center and radius, the rest will be taken
care of by the function circle():


var circle = function(cx,cy,r) {
context.moveTo(cx+r,cy);
context.arc(cx,cy,r,0,Math.PI*2.0,0);
};


Especially for circle diagrams, also called pie charts, specifying the angles in
radians seems hardly intuitive. Our function sector() does the tedious conver-
sion chore for us and allows us to specify start and end angles in degrees:


var sector = function(cx,cy,r,
startAngle,endAngle, anticlockwise
) {
context.moveTo(cx,cy);
context.arc(
cx,cy,r,
startAngle(Math.PI/180.0),
endAngle
(Math.PI/180.0),
anticlockwise
);
context.closePath();
};


Now, just a few lines of code are enough to draw circles and pie charts without
losing track:


context.beginPath();
circle(300,400,250);
circle(300,400,160);
circle(300,400,60);
sector(905,400,250,-90,30,0);
sector(900,410,280,30,150,0);
sector(895,400,230,150,270,0);
context.stroke();


Figure 5.13 shows the result.

Free download pdf