JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="can" width="600" height="600" style="width:600px;height:600px;"></canvas>
JavaScript
var canvas = document.getElementById("can");
var ctx = canvas.getContext("2d");
// Assume ctx is canvas 2D Context and ready to render to
var width = ctx.canvas.width;
var height = ctx.canvas.height;
var center = {
x: width / 2,
y: height / 2
};
canvas.addEventListener('mousemove', function(){
var mouse = {};
mouse.x = event.offsetX;
mouse.y = event.offsetY;
if(mouse.x === undefined){ // if firefox
mouse.x = event.clientX;
mouse.y = event.clientY;
}
// Substract offset (so it's centered at 0,0)
mouse.x -= center.x;
mouse.y -= center.y;
drawFibonacciSpiral({x:0, y:0}, mouse);
});
var drawFibonacciSpiral = function(p1, p2){
ctx.clearRect(0, 0, width, height);
// Draw coord axis -> center viewport at 0,0
drawStroke([{x:0, y:-center.y}, {x:0, y:center.y}], center, "gray");
drawStroke([{x:-center.x, y:0}, {x:center.x, y:0}], center,"gray");
// Draw spiral -> center viewport at 0,0
drawStroke(getSpiral(p1, p2, getDistance({x:0,y:0},center)), center);
};
var getDistance = function(p1, p2){
return Math.sqrt(Math.pow(p1.x-p2.x, 2) + Math.pow(p1.y-p2.y, 2));
};
var getAngle = function(p1, p2){
return Math.atan2(p2.y-p1.y, p2.x-p1.x);
};
var drawStroke = function(points, offset, strokeColor){
// Default value
offset = offset || {x:0,y:0}; // Offset to center on screen
strokeColor = strokeColor || "black";
ctx.strokeStyle = strokeColor;
ctx.beginPath();
var p = points[0];
ctx.moveTo(offset.x + p.x, offset.y + p.y);
for(var i = 1; i < points.length; i++){
p = points[i];
ctx.lineTo(offset.x + p.x, offset.y + p.y);
}
ctx.stroke(); // draw it all
};
var FibonacciGenerator = function(){
var thisFibonacci = this;
// Start with 0 1 2... instead of the real sequence 0 1 1 2...
thisFibonacci.array = [0, 1, 2];
thisFibonacci.getDiscrete = function(n){
// If the Fibonacci number is not in the array,...