-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
44 lines (37 loc) · 1.4 KB
/
script.js
File metadata and controls
44 lines (37 loc) · 1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
document.addEventListener("DOMContentLoaded", () => {
const box = document.querySelector('.centered-box');
const boxWidth = box.offsetWidth;
const boxHeight = box.offsetHeight;
let x = (window.innerWidth - boxWidth) / 2;
let y = (window.innerHeight - boxHeight) / 2;
let xSpeed = 0;
let ySpeed = 0;
const escapeDistance = 100;
function moveBox() {
x += xSpeed;
y += ySpeed;
x = Math.max(0, Math.min(x, window.innerWidth - boxWidth));
y = Math.max(0, Math.min(y, window.innerHeight - boxHeight));
box.style.transform = `translate(${x}px, ${y}px)`;
requestAnimationFrame(moveBox);
}
function onMouseMove(event) {
const mouseX = event.clientX;
const mouseY = event.clientY;
const boxRect = box.getBoundingClientRect();
const boxCenterX = boxRect.left + boxRect.width / 2;
const boxCenterY = boxRect.top + boxRect.height / 2;
const distanceX = mouseX - boxCenterX;
const distanceY = mouseY - boxCenterY;
const distance = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
if (distance < escapeDistance) {
xSpeed = -distanceX / distance * 1.1;
ySpeed = -distanceY / distance * 1.1;
} else {
xSpeed = 0;
ySpeed = 0;
}
}
document.addEventListener('mousemove', onMouseMove);
moveBox();
});