<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;
		}

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

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

		// 判断鼠标滚轮向上移动还是向下移动
		const direction = ev.evt.deltaY > 0 ? -1 : 1;

		// 新的缩放
		const x = direction > 0 ? scaleX * SCALE_BY : scaleX / SCALE_BY;
		const y = direction > 0 ? scaleY * SCALE_BY : scaleY / SCALE_BY;
		stage.value?.scale({ x, y });

		const position = {
			x: pointer!.x - mousePointTo.x * x,
			y: pointer!.y - mousePointTo.y * y,
		};
		stage.value!.position(position);
	});
};
const initial = () => {
	stage.value = new Konva.Stage({ container: 'container', width: width.value, height: height.value, draggable: true });
	const layer = new Konva.Layer();
	stage.value.add(layer);

	const group = new Konva.Group({ x: 120, y: 40, rotation: 20, draggable: true });
	const colors = ['red', 'orange', 'yellow'];
	for (let i = 0; i < 3; i++) {
		const rect = new Konva.Rect({
			x: i * 30,
			y: i * 30,
			width: 100,
			height: 20,
			name: `color${colors[i]}`,
			fill: colors[i],
			stroke: 'black',
			strokeWidth: 4,
		});
		group.add(rect);
	}

	zoomed();
	layer.add(group);
};

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

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

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