<script lang="ts" setup>
import { useWindowSize } from '@vueuse/core';
import { onMounted, ref } from 'vue';
import Konva from 'konva/lib';
import { Stage } from 'konva/lib/Stage';

const { width, height } = useWindowSize();
const stage = ref<Stage>();
const SCALE_BY = 1.1;

/**
 * * 画布缩放
 */
const zoomed = () => {
	stage.value?.on('wheel', ev => {
		if (!stage.value) return;
		if (!ev.evt.ctrlKey) return;
		ev.evt.preventDefault();

		// 未缩放之前，缩放比例X和Y轴
		const oldScaleX = stage.value?.scaleX();
		const oldScaleY = stage.value?.scaleY();

		// 当前鼠标位置
		const pointer = stage.value?.getPointerPosition();
		const mousePointTo = {
			x: (pointer!.x - stage.value?.x()) / oldScaleX,
			y: (pointer!.y - stage.value?.y()) / oldScaleY,
		};

		const direction = ev.evt.deltaY > 0 ? -1 : 1;

		// 为画布设置新的缩放比例
		const newScaleX = direction > 0 ? oldScaleX * SCALE_BY : oldScaleX / SCALE_BY;
		const newScaleY = direction > 0 ? oldScaleY * SCALE_BY : oldScaleY / SCALE_BY;
		stage.value?.scale({ x: newScaleX, y: newScaleY });

		// 计算当前鼠标位置
		const newPosition = {
			x: pointer!.x - mousePointTo.x * newScaleX,
			y: pointer!.y - mousePointTo.y * newScaleY,
		};
		stage.value?.position(newPosition);
	});
};

const initial = () => {
	stage.value = new Konva.Stage({ container: 'container', width: width.value, height: height.value });
	const layer = new Konva.Layer({ draggable: true });

	// 限制横向移动
	const horizontally = new Konva.Rect({
		x: 20,
		y: 20,
		width: 100,
		height: 100,
		fill: 'red',
		draggable: true,
		dragBoundFunc(pos) {
			return {
				x: pos.x,
				y: this.absolutePosition().y,
			};
		},
	});
	layer.add(horizontally);

	const vertically = new Konva.Rect({
		x: 160,
		y: 20,
		width: 100,
		height: 100,
		fill: 'green',
		draggable: true,
		dragBoundFunc(pos) {
			return { x: this.absolutePosition().x, y: pos.y };
		},
	});
	layer.add(vertically);

	stage.value.add(layer);
	zoomed();
};

onMounted(() => {
	initial();
});
</script>

<template>
	<div id="container"></div>
</template>

<style lang="scss" scoped></style>
