Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing a spiral on an HTML canvas using JavaScript

Tags:

I have searched and haven't found anything really on how to draw spirals in canvas using JavaScript.

I thought it might be possible to do it with the bezier curve and if that didn't work use lineTo(), but that seemed a lot harder.

Also, to do that I'm guessing I would have to use trigonometry and graphing with polar coordinates and its been a while since I did that. If that is the case could you point me in the right direction on the math.

like image 317
qw3n Avatar asked Jul 26 '11 01:07

qw3n


People also ask

How do you make a spiral in HTML?

To draw a spiral with HTML5 canvas, we can place our drawing cursor in the center of the canvas, iteratively increase the radius and angle about the center, and then draw a super short line from the previous point to the current point.

Does canvas work with JavaScript?

<canvas> is an HTML element which can be used to draw graphics via scripting (usually JavaScript).

How do I make a circle canvas in HTML?

The arc() method creates an arc/curve (used to create circles, or parts of circles). Tip: To create a circle with arc(): Set start angle to 0 and end angle to 2*Math. PI. Tip: Use the stroke() or the fill() method to actually draw the arc on the canvas.


2 Answers

The Archimedean spiral is expressed as r=a+b(angle). Convert that into x, y coordinate, it will be expressed as x=(a+b*angle)*cos(angle), y=(a+b*angle)*sin(angle). Then you can put angle in a for loop and do something like this:

for (i=0; i< 720; i++) {   angle = 0.1 * i;   x=(1+angle)*Math.cos(angle);   y=(1+angle)*Math.sin(angle);   context.lineTo(x, y); } 

Note the above assumes a = 1 and b = 1.

Here is a jsfiddle link: http://jsfiddle.net/jingshaochen/xJc7M/

like image 158
Jingshao Chen Avatar answered Sep 20 '22 20:09

Jingshao Chen


This is a slightly-changed, javascript-ified version of a Java spiral I once borrowed from here

It uses lineTo() and its not all that hard.

<!DOCTYPE HTML> <html><body> <canvas id="myCanvas" width="300" height="300" style="border:1px solid #c3c3c3;"></canvas> <script type="text/javascript">     var c=document.getElementById("myCanvas");     var cxt=c.getContext("2d");     var centerX = 150;     var centerY = 150;     cxt.moveTo(centerX, centerY);      var STEPS_PER_ROTATION = 60;     var increment = 2*Math.PI/STEPS_PER_ROTATION;            var theta = increment;      while( theta < 40*Math.PI) {       var newX = centerX + theta * Math.cos(theta);        var newY = centerY + theta * Math.sin(theta);        cxt.lineTo(newX, newY);       theta = theta + increment;     }     cxt.stroke(); </script></body></html> 
like image 31
icchanobot Avatar answered Sep 21 '22 20:09

icchanobot