admin管理员组

文章数量:1336414

I would like to get some tips of how to draw a cogwheel shape with HTML5 canvas + Javascript.

Not importing a picture, but actually making the shape yourself.

I supose it would be some kind of loop depending on how many teeths you want the cog to have etc.

But I dont know the math for the trigonemetri etc.

I would like to get some tips of how to draw a cogwheel shape with HTML5 canvas + Javascript.

Not importing a picture, but actually making the shape yourself.

I supose it would be some kind of loop depending on how many teeths you want the cog to have etc.

But I dont know the math for the trigonemetri etc.

Share Improve this question edited May 8, 2014 at 13:44 Qantas 94 Heavy 16k31 gold badges72 silver badges88 bronze badges asked May 7, 2014 at 20:06 timpal0ltimpal0l 631 silver badge5 bronze badges 8
  • It would probably be easiest to split it up into multiple shapes. – ndugger Commented May 7, 2014 at 20:08
  • Would that be smart if I also want to make it to rotate? I mean its symmetric, so why split it up to diffrent parts? – timpal0l Commented May 7, 2014 at 20:09
  • You didn't say that it's symmetrical. A gear does not have to be symmetrical, after all. What matters is the number and size of the teeth on the gear. You will have to split the diameter up to find your points, then draw to those points, all the way around the circumference of your object. – Jason M. Batchelor Commented May 7, 2014 at 20:14
  • Not exactly what you're looking for, but this might be helpful: Gears/Cogs effect using HTML5, CSS & jQuery – APAD1 Commented May 7, 2014 at 20:15
  • 1 The math for cogwheels and gears can be found in references like the excellent Machinery's Handbook. For instance in this case the chapter on gears covers: spur, internal, bevel, worm, helical, herringbone, panetary and ratchet gearing. Check your local library if the purchase price is out of your range. – Jason Aller Commented May 7, 2014 at 20:25
 |  Show 3 more ments

2 Answers 2

Reset to default 10

A cogwheel / gear is not so plicated to render - initialize some basic values for inner and outer radius, taper values and angle step.

Example values:

var cx      = 200,                    // center x
    cy      = 200,                    // center y
    notches = 7,                      // num. of notches
    radiusO = 180,                    // outer radius
    radiusI = 130,                    // inner radius
    taperO  = 50,                     // outer taper %
    taperI  = 35,                     // inner taper %

    // pre-calculate values for loop

    pi2     = 2 * Math.PI,            // cache 2xPI (360deg)
    angle   = pi2 / (notches * 2),    // angle between notches
    taperAI = angle * taperI * 0.005, // inner taper offset (100% = half notch)
    taperAO = angle * taperO * 0.005, // outer taper offset
    a       = angle,                  // iterator (angle)
    toggle  = false;                  // notch radius level (i/o)

Set up the canvas and use a single loop to iterate through a circle based on these values and a toggle switch which will draw every other level outer to inner and inner to outer lines:

// move to starting point
ctx.moveTo(cx + radiusO * Math.cos(taperAO), cy + radiusO * Math.sin(taperAO));

// loop
for (; a <= pi2; a += angle) {

    // draw inner to outer line
    if (toggle) {
        ctx.lineTo(cx + radiusI * Math.cos(a - taperAI),
                   cy + radiusI * Math.sin(a - taperAI));
        ctx.lineTo(cx + radiusO * Math.cos(a + taperAO),
                   cy + radiusO * Math.sin(a + taperAO));
    }

    // draw outer to inner line
    else {
        ctx.lineTo(cx + radiusO * Math.cos(a - taperAO),  // outer line
                   cy + radiusO * Math.sin(a - taperAO));
        ctx.lineTo(cx + radiusI * Math.cos(a + taperAI),  // inner line
                   cy + radiusI * Math.sin(a + taperAI));
    }

    // switch level
    toggle = !toggle;
}

// close the final line
ctx.closePath();

Holes

Method 1

One way to create the center hole is to use position:

// "erase" mode (term simplified)
ctx.globalCompositeOperation = 'destination-out';

// create circle (full arc)
ctx.beginPath();
ctx.moveTo(cx + radiusH, cy);
ctx.arc(cx, cy, radiusH, 0, pi2);
ctx.closePath();

// creates the hole
ctx.fill();

// reset p. mode
ctx.globalCompositeOperation = 'source-over';

Fiddle

Method 2

The other way is to use the fill-rule even-odd by adding the arc path for the whole before filling and stroking. Note that you need to use moveTo() to break up the path for stroking:

// without filling/stroking, continue with:

// Punch hole
ctx.moveTo(cx + radiusH, cy);
ctx.arc(cx, cy, radiusH, 0, pi2);

// now fill using even-odd rule
ctx.fillStyle = '#aaa';
ctx.fill("evenodd");

// stroke
ctx.lineWidth = 2;
ctx.strokeStyle = '#000';
ctx.stroke();

Fiddle

Here is an example of code that draws a gear in ActionScript3 (found it at this link: http://www.funky-monkey.nl/blog/2010/04/drawing-shapes-in-as3-a-class-to-draw-an-arc-star-gear-cog-wedge-and-a-burst/), which is an ECMAScript based language. With some futzing around with a library such as Raphael.js, it should be possible to do much the same thing.

The general approach could be something along these lines:

function() {
 // store number of sides, and where you are starting
 var step, qtrStep, start, n, dx, dy;
 // calculate length of sides
step = [findDiameter] / number-of-sides;
    qtrStep = [break each step into parts];
// calculate starting angle in radians
 start = (angle / 180) * Math.PI;
 // move your pen to the starting position
    // draw lines
for (numberofsides ... iterate) {
    // position at the starting point of the tooth
            // draw to the end point of the first side of the tooth
            // draw to the end point of the top of the tooth
            // draw to the end point of the bottom of the third side of the tooth
            // draw to the starting point of the next tooth
    }
}

本文标签: javascriptHow to draw a Cogwheel in HTML5 canvasStack Overflow