-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathkeyframes.proximity.js
More file actions
77 lines (63 loc) · 2.71 KB
/
keyframes.proximity.js
File metadata and controls
77 lines (63 loc) · 2.71 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
export default (Keyframes) => {
Keyframes.prototype.proximity = function (onMove) {
this.onMouseMove = (e) => {
const mouse = {
x: e.pageX,
y: e.pageY,
};
// Target edge
const target = this.elem.getBoundingClientRect();
const targetCenter = {
x: Math.floor(target.left + (target.width / 2)),
y: Math.floor(target.top + (target.height / 2)),
};
const angle = Math.atan2(mouse.y - targetCenter.y, mouse.x - targetCenter.x);
const cosAngle = Math.abs(Math.cos(angle));
const sinAngle = Math.abs(Math.sin(angle));
const magnitude = target.width / 2 * sinAngle <= target.height / 2 * cosAngle ?
target.width / 2 / cosAngle :
target.height / 2 / sinAngle;
const targetEdge = {
x: targetCenter.x + Math.cos(angle) * magnitude,
y: targetCenter.y + Math.sin(angle) * magnitude,
};
// Viewport edge
const viewport = {
width: window.innerWidth,
height: window.innerHeight,
};
const viewPortMagnitude = viewport.width / 2 * sinAngle <= viewport.height / 2 * cosAngle ?
viewport.width / 2 / cosAngle :
viewport.height / 2 / sinAngle;
const viewPortEdge = {
x: targetCenter.x + Math.cos(angle) * viewPortMagnitude,
y: targetCenter.y + Math.sin(angle) * viewPortMagnitude,
};
// Distances
const calculateDistance = (vector) => {
const offsets = {
top: target.top - vector.y,
right: vector.x - (target.left + target.width),
bottom: vector.y - (target.top + target.height),
left: target.left - vector.x,
};
const dx = Math.max(offsets.left, 0, offsets.right) ** 2;
const dy = Math.max(offsets.top, 0, offsets.bottom) ** 2;
return Math.sqrt(dx + dy);
};
const mouseDistance = calculateDistance(mouse);
const viewPortDistance = calculateDistance(viewPortEdge);
const distancePercentage = 100 - Math.round((mouseDistance / viewPortDistance) * 100);
onMove({
mouse,
mouseDistance,
viewPortDistance,
distancePercentage,
targetEdge,
viewPortEdge,
collision: !mouseDistance,
});
};
window.addEventListener('mousemove', this.onMouseMove);
};
};