JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="canvas"></canvas>
CSS
body {
height: 100vh;
width: 100vw;
}
canvas {
display: block;
position: absolute;
z-index: 500;
border: 2px solid red;
}
JavaScript
window.requestAnimFrame = (function() {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
var ctx,
widthCanvas,
heightCanvas,
leftEye,
rightEye,
mouse;
Eye = function(pos) {
this.pos = {
x: pos.x,
y: pos.y
};
this.center = {
x: pos.x,
y: pos.y
};
this.translation = {
x: (window.innerWidth / 2 - canvas.width / 2) + this.center.x,
y: this.center.y
};
}
Eye.prototype.draw = function() {
ctx.beginPath();
ctx.arc(this.pos.x, this.pos.y, 7, 0, Math.PI * 2);
ctx.fillStyle = '#333';
ctx.fill();
ctx.beginPath();
ctx.arc(this.pos.x, this.pos.y - 4, 3, 0, Math.PI * 2);
ctx.fillStyle = '#fff';
ctx.fill();
}
Eye.prototype.update = function() {
var deltaX = mouse.x - this.translation.x;
var deltaY = mouse.y - this.translation.y;
var mag = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
var angleRad = Math.atan2(deltaY, deltaX);
var newPosX = this.center.x + 6 * Math.cos(angleRad);
var newPosY = this.center.y + 6 * Math.sin(angleRad);
this.pos.x += (newPosX - this.pos.x) / 5;
this.pos.y += (newPosY - this.pos.y) / 5;
}
var init = function() {
var canvas = document.getElementById("canvas");
var $canvas = $('#canvas');
ctx = canvas.getContext('2d');
container = $("body");
widthCanvas = 300;
heightCanvas = 250;
$(window).resize(resizeCanvas);
function resizeCanvas() {
widthCanvas = $canvas.attr('width', $(container).width());
heightCanvas = $canvas.attr('height', $(container).height());
}
resizeCanvas();
canvas.width = widthCanvas;
canvas.height = heightCanvas;
leftEye = new Eye({
x: 130,
y: 95
});
rightEye = new Eye({
x: 160,
y: 85
});
mouse = {
x: 0,
y: 0
};
bindEventHandlers();
draw();
}
var draw = function() {
...