OLD | NEW |
(Empty) | |
| 1 var NumTeeth = 24; |
| 2 var Delta = Math.PI/90; |
| 3 var NumGears = 60; |
| 4 var FaceColors = ["#000099", "#006600", "#990000", "#EEEE00"]; |
| 5 var SideColors = ["#0000FF", "#009900", "#FF0000", "#CCCC00"]; |
| 6 |
| 7 |
| 8 function drawGear(ctx, r) { |
| 9 var dT = Math.PI*2/NumTeeth; |
| 10 var dTq = dT/4; |
| 11 var outer = r; |
| 12 var inner = 0.7 * r; |
| 13 ctx.beginPath(); |
| 14 for (var i=0; i<NumTeeth; i+=2) { |
| 15 ctx.lineTo(Math.sin(dT*i-dTq)*outer, Math.cos(dT*i-dTq)*outer); |
| 16 ctx.lineTo(Math.sin(dT*i+dTq)*inner, Math.cos(dT*i+dTq)*inner); |
| 17 ctx.lineTo(Math.sin(dT*(i+1)-dTq)*inner, Math.cos(dT*(i+1)-dTq)*inner); |
| 18 ctx.lineTo(Math.sin(dT*(i+1)+dTq)*outer, Math.cos(dT*(i+1)+dTq)*outer); |
| 19 } |
| 20 ctx.closePath(); |
| 21 ctx.stroke(); |
| 22 }; |
| 23 |
| 24 function draw3DGear(ctx, angle, faceColor, sideColor, r) { |
| 25 ctx.fillStyle = faceColor; |
| 26 ctx.strokeStyle = sideColor; |
| 27 ctx.rotate(angle); |
| 28 drawGear(ctx, r); |
| 29 for (var i=0; i < 20; i++) { |
| 30 ctx.rotate(-angle); |
| 31 ctx.translate(0.707, 0.707); |
| 32 ctx.rotate(angle); |
| 33 drawGear(ctx, r); |
| 34 } |
| 35 ctx.fill() |
| 36 ctx.rotate(-angle); |
| 37 } |
| 38 |
| 39 function draw3DGearAt(ctx, x, y, r, angle, faceColor, sideColor) { |
| 40 ctx.save(); |
| 41 ctx.translate(x, y); |
| 42 draw3DGear(ctx, angle, faceColor, sideColor, r); |
| 43 ctx.restore(); |
| 44 } |
| 45 |
| 46 var anim = function() { |
| 47 var canvas = document.getElementById('gears'); |
| 48 var ctx = canvas.getContext("2d"); |
| 49 var ticks=0; |
| 50 var rotation = 0; |
| 51 var gears = []; |
| 52 |
| 53 for (var i=0; i<NumGears; i++) { |
| 54 color = Math.floor(Math.random()*FaceColors.length); |
| 55 gears.push({ |
| 56 x: Math.random()*500, |
| 57 y: Math.random()*500, |
| 58 r: Math.random()*100+5, |
| 59 faceColor: FaceColors[color], |
| 60 sideColor: SideColors[color] |
| 61 }); |
| 62 } |
| 63 |
| 64 function draw() { |
| 65 ctx.resetTransform(); |
| 66 ctx.fillStyle = 'white'; |
| 67 ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height); |
| 68 |
| 69 rotation += Delta; |
| 70 if (rotation >= Math.PI*2) { |
| 71 rotation = 0; |
| 72 } |
| 73 |
| 74 for (var i=0; i < gears.length; i++) { |
| 75 draw3DGearAt(ctx, gears[i].x, gears[i].y, gears[i].r, rotation, |
| 76 gears[i].faceColor, gears[i].sideColor); } |
| 77 |
| 78 ticks++; |
| 79 requestAnimationFrame(draw); |
| 80 } |
| 81 |
| 82 requestAnimationFrame(draw); |
| 83 |
| 84 |
| 85 function fps() { |
| 86 console.log(ticks); |
| 87 ticks = 0; |
| 88 } |
| 89 |
| 90 setInterval(fps, 1000); |
| 91 }(); |
| 92 |
| 93 |
OLD | NEW |