summaryrefslogtreecommitdiff
path: root/packages/frontend/src/components/CkFollowMouse.vue
blob: ce7e3c79a8ac9ccbe398b6d5f29652edcdf26e4d (plain)
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
78
79
80
81
82
83
84
85
86
<!--
SPDX-FileCopyrightText: leah and other Cutiekey contributors
SPDX-License-Identifier: AGPL-3.0-only
-->

<template>
<span ref="container" :class="$style.root">
	<span ref="el" :class="$style.inner" style="position: absolute">
		<slot></slot>
	</span>
</span>
</template>

<script lang="ts" setup>
import { onMounted, onUnmounted, shallowRef } from 'vue';
const el = shallowRef<HTMLElement>();
const container = shallowRef<HTMLElement>();
const props = defineProps({
	x: {
		type: Boolean,
		default: true,
	},
	y: {
		type: Boolean,
		default: true,
	},
	speed: {
		type: String,
		default: '0.1s',
	},
	rotateByVelocity: {
		type: Boolean,
		default: true,
	},
});

let lastX = 0;
let lastY = 0;
let oldAngle = 0;

function lerp(a, b, alpha) {
	return a + alpha * (b - a);
}

const updatePosition = (mouseEvent: MouseEvent) => {
	if (el.value && container.value) {
		const containerRect = container.value.getBoundingClientRect();
		const newX = mouseEvent.clientX - containerRect.left;
		const newY = mouseEvent.clientY - containerRect.top;
		let transform = `translate(calc(${props.x ? newX : 0}px - 50%), calc(${props.y ? newY : 0}px - 50%))`;
		if (props.rotateByVelocity) {
			const deltaX = newX - lastX;
			const deltaY = newY - lastY;
			const angle = lerp(
				oldAngle,
				Math.atan2(deltaY, deltaX) * (180 / Math.PI),
				0.1,
			);
			transform += ` rotate(${angle}deg)`;
			oldAngle = angle;
		}
		el.value.style.transform = transform;
		el.value.style.transition = `transform ${props.speed}`;
		lastX = newX;
		lastY = newY;
	}
};

onMounted(() => {
	window.addEventListener('mousemove', updatePosition);
});

onUnmounted(() => {
	window.removeEventListener('mousemove', updatePosition);
});
</script>

<style lang="scss" module>
.root {
	position: relative;
	display: inline-block;
}
.inner {
	transform-origin: center center;
}
</style>