HTML Canvas Line draw connected lines via for loop
<html> <head> <script> window.onload = function(){ var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d"); //from w w w . j a v a 2 s. c o m 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 without the teeth var midRadius = innerRadius * 1.6; // radius of the hole var holeRadius = 10; var numPoints = 30; // draw gear teeth context.beginPath(); context.lineJoin = "bevel"; for (var n = 0; n < numPoints; n++) { var radius = null; // draw tip of teeth on even iterations if (n % 2 == 0) { radius = outerRadius; } else { radius = innerRadius; } var theta = ((Math.PI * 2) / numPoints) * (n + 1); var x = (radius * Math.sin(theta)) + centerX; var y = (radius * Math.cos(theta)) + centerY; // if first iteration, use moveTo() to position // the drawing cursor if (n == 0) { context.moveTo(x, y); } // if any other iteration, use lineTo() to connect sub paths else { context.lineTo(x, y); } } context.closePath(); // define the line width and stroke color context.lineWidth = 5; context.strokeStyle = "red"; context.stroke(); // draw gear body context.beginPath(); context.arc(centerX, centerY, midRadius, 0, 2 * Math.PI, false); // draw gear hole context.beginPath(); context.arc(centerX, centerY, holeRadius, 0, 2 * Math.PI, false); context.fillStyle = "white"; context.fill(); context.strokeStyle = "#004CB3"; context.stroke(); }; </script> </head> <body> <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;"> </canvas> </body> </html>