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

<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', e => {
		if (!stage.value) return;
		if (!e.evt.ctrlKey) return;
		e.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,
		};

		// 判断是向上滚动鼠标还是向下滚动鼠标，向下滚动为正。向上滚动为负
		let direction = e.evt.deltaY > 0 ? -1 : 1;

		// 新的缩放比例X轴
		const newScaleX = direction > 0 ? oldScaleX * SCALE_BY : oldScaleX / SCALE_BY;
		// 新的缩放比例Y轴
		const newScaleY = direction > 0 ? oldScaleY * SCALE_BY : oldScaleY / SCALE_BY;
		stage.value!.scale({ x: newScaleX, y: newScaleY });

		// 计算当前鼠标和移动之前鼠标乘以新的缩放比例大小，保持画布变化后鼠标图形依旧在鼠标相对位置上
		const newPos = {
			x: pointer!.x - mousePointTo.x * newScaleX,
			y: pointer!.y - mousePointTo.y * newScaleY,
		};
		stage.value!.position(newPos);
	});
};

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

	// 创建文本
	const text = new Konva.Text({
		x: 10,
		y: 10,
		fontFamily: 'Calibri',
		fontSize: 20,
		text: '',
		fill: 'black',
	});
	layer.add(text);

	// 创建元素
	const circle = new Konva.Circle({
		x: stage.value!.width() / 2,
		y: stage.value!.height() / 2,
		radius: 70,
		fill: 'red',
		stroke: 'black',
		strokeWidth: 4,
	});
	layer.add(circle);

	// 添加监听事件
	circle.on('mouseover mousedown mouseup', function () {
		text.text('鼠标事件：mouseover mousedown mouseup');
	});
	circle.on('mouseout', function () {
		text.text('鼠标离开');
	});

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

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