<html>
<body>
<canvas id="canvas"></canvas>
</body>
</html>
* {
box-sizing: border-box;
}
html,
body,
canvas {
display: block;
position: relative;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
canvas {
background-color: rgb(80, 80, 80);
}
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
let width = window.innerWidth;
let height = window.innerHeight;
let theta = 1.57;
let mx = 0;
let my = 0;
let dx; // Adjacent
let dy; // Opposite
const draw = () => {
const eye = {
x: width / 2,
y: height / 2,
radius: 50
};
dx = mx - eye.x;
dy = my - eye.y;
theta = Math.atan2(dy, dx);
const pupil = {
x: eye.x + Math.cos(theta) * 20,
y: eye.y + Math.sin(theta) * 20,
radius: eye.radius / 2
};
ctx.clearRect(0, 0, width, height);
/* Draw Eye */
ctx.beginPath();
ctx.arc(eye.x, eye.y, eye.radius, 0, Math.PI * 2, true);
ctx.fillStyle = "rgb(255, 255, 255)";
ctx.fill();
ctx.closePath();
/* Draw Pupil */
ctx.beginPath();
ctx.arc(pupil.x, pupil.y, pupil.radius, 0, Math.PI * 2, true);
ctx.fillStyle = "rgb(0, 0, 0)";
ctx.fill();
ctx.closePath();
window.requestAnimationFrame(draw);
};
const handleResize = () => {
console.log("resize");
width = window.innerWidth;
height = window.innerHeight;
/* Set the size on canvas instead of CSS to avoid strecthing */
canvas.width = width;
canvas.height = height;
};
const handleMousemove = e => {
mx = e.clientX;
my = e.clientY;
};
window.addEventListener("resize", handleResize);
window.addEventListener("mousemove", handleMousemove);
handleResize();
draw();
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.