Creating patterns with loops: drawing a gear

In this recipe, we'll create a mechanical gear by iteratively drawing a radial zigzag to form teeth and then drawing circles to form the body of the gear.

Creating patterns with loops: drawing a gear

How to do it...

Follow these steps to draw a gear centered on the canvas:

  1. Define a 2D canvas context and set the gear properties:
    window.onload = function(){ var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d"); // gear position var centerX = canvas.width / 2; var centerY = canvas.height / 2; // radius of the teeth tips var outerRadius = 95; // radius of the teeth intersections var innerRadius = 50; // radius of the gear ...

Get HTML5 Canvas Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.