Interactive Spiral

An animated spiral that follows the mouse cursor.

by Tomás Antunes

HTML

<canvas id="my-canvas"></canvas>

CSS

#my-canvas {
  border: 1px solid #000;
}

JavaScript

var my_canvas = document.getElementById('my-canvas');
var context = my_canvas.getContext('2d');
var w = window.innerWidth;
var h = window.innerHeight;
var x = 0;
var y = 0;
var cx = w/2;
var cy = h/2;
var angle_step = 1;
var frame_count = 0;
var animation_frame = 0;
var animation_speed = 2;

my_canvas.width = w;
my_canvas.height = h;

context.strokeStyle = "rgb(129,155,202)";
context.lineWidth = 5;

requestAnimationFrame(draw);

my_canvas.onmousemove = function(e) { 
  cx = e.clientX;
  cy = e.clientY;
};

function draw() {
  frame_count += 1;
  context.clearRect(0,0,w,h);
  context.save();
  context.translate(cx,cy);
  animation_frame = 360 - (frame_count * animation_speed % 360);
  context.rotate(animation_frame * Math.PI / 180);
  context.beginPath();
  context.moveTo(0,0);
  for (i=0; i< 5660; i++) {
    context.rotate(angle_step * Math.PI / 180);
    x += 0.2;
    context.lineTo(x, y);
  }
  x = 0;
  context.stroke();
  context.restore();
  requestAnimationFrame(draw);
}