Line data Source code
1 : <script setup lang="ts">
2 : import { computed, ref, useTemplateRef } from 'vue'
3 :
4 2355 : const zoomPane = useTemplateRef('zoomPane')
5 :
6 11 : const zoom = ref(1.0)
7 11 : const panX = ref(0.0)
8 11 : const panY = ref(0.0)
9 :
10 0 : function handleWheel(e: WheelEvent) {
11 0 : const zoomPaneEl = zoomPane.value
12 0 : if (!zoomPaneEl || (e.deltaY < 0 ? zoom.value > 1200 : zoom.value < -500))
13 0 : return
14 :
15 0 : zoom.value -= e.deltaY
16 0 : const { x, y, width, height } = zoomPaneEl.getBoundingClientRect()
17 0 : const offsetX = e.clientX - x - width / 2
18 0 : const offsetY = e.clientY - y - height / 2
19 0 : const scaler = 1.1 ** (e.deltaY / -30)
20 :
21 0 : panY.value = panY.value * scaler - offsetY * (scaler - 1)
22 0 : panX.value = panX.value * scaler - offsetX * (scaler - 1)
23 : }
24 :
25 11 : let dragging = false
26 0 : function handleDown(e: PointerEvent) {
27 0 : if (e.button !== 0 && e.button !== 1) return
28 :
29 0 : const zoomPaneEl = zoomPane.value
30 0 : if (!zoomPaneEl) return
31 0 : zoomPaneEl.parentElement?.focus()
32 :
33 0 : zoomPaneEl.setPointerCapture(e.pointerId)
34 0 : dragging = true
35 : }
36 0 : function handleMove(e: PointerEvent) {
37 0 : if (!dragging) return
38 0 : panX.value += e.movementX
39 0 : panY.value += e.movementY
40 : }
41 :
42 11 : const transform = computed(() => {
43 11 : const scale = 1.1 ** (zoom.value / 30)
44 : const matrix = [scale, 0, 0, scale, panX.value, panY.value]
45 11 : return `matrix(${matrix.join(',')})`
46 : })
47 11 : </script>
48 : <template>
49 14 : <div
50 : ref="zoomPane"
51 : class="place-content-center contain-size"
52 : @wheel="handleWheel"
53 : @pointerdown.prevent="handleDown"
54 : @pointermove="handleMove"
55 : @pointerup="dragging = false"
56 : @pointercancel="dragging = false"
57 : >
58 : <slot :style="{ transform }" />
59 : </div>
60 : </template>
|