Cogwheels with Raphaël – part 1

As a way to learn Raphaël I want play with cogwheels. I will build this up gradually. This is the first installment. Let’s begin with two cogs. Below is a working example of them, press the buttons to try the different easings that are supported by the Raphaël animate method.

First create canvas.

var r = Raphael("canvas", 600, 450);

Next define a cogwheel() function, that takes radius and number of teeth as arguments.

function cogwheel(radius, teeth)
	var path = getPath(0, 0, radius, teeth);
	var cog = r.path(path);
	return cog; 

Finally create two cogs. The radius and number of teeth of the second wheel are three times that of the first. See how we shift the wheels and set attributes like fill gradient and stroke width.

small = cogwheel(50,13).translate(343,88).attr({
	gradient: '90-#526c7a-#64a0c1',  
	stroke: '#3b4449',  
	'stroke-width': 3,  
	'stroke-linejoin': 'round'
big = cogwheel(150,39).translate(200,230).attr({
	gradient: '90-#7a6c52-#a0c164',  
	stroke: '#49443b',  
	'stroke-width': 3,  
	'stroke-linejoin': 'round'

To generate a path that describes a cogwheel, the cogwheel() uses function getPath(). This returns a string holding the path for a cogwheel. A point [x,y] on the x-axis is rotated by an angle equivalent to 360°/(number of teeth). For 12 teeth this would be 30°. Since a tooth consists of a convex and a concave half circle, we also need a point in the middle, hence the rotation of [x,y] by sector/2. Note how we add the coordinates of the centre point [cx,cy] to the path. This is so as to make the rotation of [x,y] around [0,0], which is the easiest.

/* now rotate */
var z = teeth;
while (z--)
	x1 = x * Math.cos(sector) - y * Math.sin(sector);
	y1 = x * Math.sin(sector) + y * Math.cos(sector);
	x2 = x * Math.cos(sector/2) - y * Math.sin(sector/2);
	y2 = x * Math.sin(sector/2) + y * Math.cos(sector/2);
	path = path + " A "+rs+","+rs+"  0 1,1 "+(cx+x2) + "," + (cy+y2); 
	path = path + " A "+rs+","+rs+"  0 0,0 "+(cx+x1) + "," + (cy+y1); 
	x = x1;
	y = y1;

This is what we have got so far. We have 12 teeth, three in each quadrant:

It is easy to add a hole in the middle. We do this by building a circle out of two half circles.

rs1 = radius / 10;
path = path + " M "+(cx-rs1)+","+cy;
path = path + " A "+rs1+","+rs1+"  0 0,0 "+(cx+rs1) + ","+cy; 
path = path + " A "+rs1+","+rs1+"  0 0,0 "+(cx-rs1) + ","+cy; 

The trick is to make the teeth go around clockwise, and the hole in the middle counter clockwise. That way the area, that this path describes, is subtracted from the object.

The last thing we need to do is to make the spokes by adding four fan-shaped holes. Each of these consists of two lines and two arcs. I spare you the maths. Here is the finished cogwheel:

Post a comment

You may use the following HTML:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>