| 1 | var ctx = document.getElementById('tutorial').getContext('2d');
|
|---|
| 2 | ctx.strokeStyle = "#fc0";
|
|---|
| 3 | ctx.lineWidth = 1.5;
|
|---|
| 4 | ctx.fillRect(0,0,300,300);
|
|---|
| 5 |
|
|---|
| 6 | // Uniform scaling
|
|---|
| 7 | ctx.save()
|
|---|
| 8 | ctx.translate(50,50);
|
|---|
| 9 | drawSpirograph(ctx,22,6,5); // no scaling
|
|---|
| 10 |
|
|---|
| 11 | ctx.translate(100,0);
|
|---|
| 12 | ctx.scale(0.75,0.75);
|
|---|
| 13 | drawSpirograph(ctx,22,6,5);
|
|---|
| 14 |
|
|---|
| 15 | ctx.translate(133.333,0);
|
|---|
| 16 | ctx.scale(0.75,0.75);
|
|---|
| 17 | drawSpirograph(ctx,22,6,5);
|
|---|
| 18 | ctx.restore();
|
|---|
| 19 |
|
|---|
| 20 | // Non uniform scaling (y direction)
|
|---|
| 21 | ctx.strokeStyle = "#0cf";
|
|---|
| 22 | ctx.save()
|
|---|
| 23 | ctx.translate(50,150);
|
|---|
| 24 | ctx.scale(1,0.75);
|
|---|
| 25 | drawSpirograph(ctx,22,6,5);
|
|---|
| 26 |
|
|---|
| 27 | ctx.translate(100,0);
|
|---|
| 28 | ctx.scale(1,0.75);
|
|---|
| 29 | drawSpirograph(ctx,22,6,5);
|
|---|
| 30 |
|
|---|
| 31 | ctx.translate(100,0);
|
|---|
| 32 | ctx.scale(1,0.75);
|
|---|
| 33 | drawSpirograph(ctx,22,6,5);
|
|---|
| 34 | ctx.restore();
|
|---|
| 35 |
|
|---|
| 36 | // Non uniform scaling (x direction)
|
|---|
| 37 | ctx.strokeStyle = "#cf0";
|
|---|
| 38 | ctx.save()
|
|---|
| 39 | ctx.translate(50,250);
|
|---|
| 40 | ctx.scale(0.75,1);
|
|---|
| 41 | drawSpirograph(ctx,22,6,5);
|
|---|
| 42 |
|
|---|
| 43 | ctx.translate(133.333,0);
|
|---|
| 44 | ctx.scale(0.75,1);
|
|---|
| 45 | drawSpirograph(ctx,22,6,5);
|
|---|
| 46 |
|
|---|
| 47 | ctx.translate(177.777,0);
|
|---|
| 48 | ctx.scale(0.75,1);
|
|---|
| 49 | drawSpirograph(ctx,22,6,5);
|
|---|
| 50 | ctx.restore();
|
|---|
| 51 | function drawSpirograph(ctx,R,r,O){
|
|---|
| 52 | var x1 = R-O;
|
|---|
| 53 | var y1 = 0;
|
|---|
| 54 | var i = 1;
|
|---|
| 55 | ctx.beginPath();
|
|---|
| 56 | ctx.moveTo(x1,y1);
|
|---|
| 57 | do {
|
|---|
| 58 | if (i>20000) break;
|
|---|
| 59 | var x2 = (R+r)*Math.cos(i*Math.PI/72) - (r+O)*Math.cos(((R+r)/r)*(i*Math.PI/72))
|
|---|
| 60 | var y2 = (R+r)*Math.sin(i*Math.PI/72) - (r+O)*Math.sin(((R+r)/r)*(i*Math.PI/72))
|
|---|
| 61 | ctx.lineTo(x2,y2);
|
|---|
| 62 | x1 = x2;
|
|---|
| 63 | y1 = y2;
|
|---|
| 64 | i++;
|
|---|
| 65 | } while (x2 != R-O && y2 != 0 );
|
|---|
| 66 | ctx.stroke();
|
|---|
| 67 | }
|
|---|