aboutsummaryrefslogtreecommitdiff
path: root/src/lib/Image/ParallaxImage.svelte
blob: 390b9c92f15d50455a06b824dc698694a6877dd4 (plain) (blame)
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
<script lang="ts">
  import { cubicOut } from 'svelte/easing';
  import { tweened } from 'svelte/motion';

  interface Props {
    source: string;
    duration?: any;
    easing?: any;
    alternativeText: string;
    classList?: string;
    style?: string;
    factor?: number;
    limit?: any;
    borderRadius?: string;
  }

  let {
    source,
    duration = 300 * 1.75,
    easing = cubicOut,
    alternativeText,
    classList = '',
    style = '',
    factor = 1.25,
    limit = 300 * 1.75,
    borderRadius = '8px'
  }: Props = $props();

  let badgeReference: HTMLImageElement = $state();
  const mouse = tweened({ x: 0, y: 0 }, { duration, easing });

  const handleMouseMove = (event: MouseEvent) => {
    const boundingRectangle = badgeReference.getBoundingClientRect();

    if ($mouse.x === 0 && $mouse.y === 0) $mouse = { x: event.clientX, y: event.clientY };

    $mouse.x +=
      (-(event.clientX - boundingRectangle.left - boundingRectangle.width / 2) - $mouse.x) * factor;
    $mouse.y +=
      (-(event.clientY - boundingRectangle.top - boundingRectangle.height / 2) - $mouse.y) * factor;
    $mouse.x = Math.max(Math.min($mouse.x, limit), -limit);
    $mouse.y = Math.max(Math.min($mouse.y, limit), -limit);
  };

  const handleMouseLeave = () => {
    $mouse = { x: 0, y: 0 };
  };
</script>

<img
  src={source}
  bind:this={badgeReference}
  style={`transform: perspective(1000px) rotateX(${$mouse.y / 10}deg) rotateY(${
    -$mouse.x / 10
  }deg); border-radius: ${borderRadius}; ${style}`}
  alt={alternativeText}
  onmousemove={handleMouseMove}
  onmouseleave={handleMouseLeave}
  class={classList}
/>