Skip to content

Instantly share code, notes, and snippets.

@icchan
Last active October 14, 2018 05:30
Show Gist options
  • Save icchan/1105803 to your computer and use it in GitHub Desktop.
Save icchan/1105803 to your computer and use it in GitHub Desktop.
Drawing a spiral on the HTML5 canvas using javascript
<!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 gap = 1.8; // increase this for spacing between spiral lines
var STEPS_PER_ROTATION = 60; // increasing this makes the curve smoother
var increment = 2*Math.PI/STEPS_PER_ROTATION;
var theta = increment;
while( theta < 20*Math.PI) {
var newX = centerX + theta * Math.cos(theta) * gap;
var newY = centerY + theta * Math.sin(theta) * gap;
cxt.lineTo(newX, newY);
theta = theta + increment;
}
cxt.stroke(); // draw the spiral
</script></body></html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment