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

const { width, height } = useWindowSize();
const circle = ref<Circle>();
const text = ref<Text>();
const stage = ref<Stage>();
const layer = ref<Layer>();
const SCALE_BY = 1.1;

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

		// 当前缩放比例，获取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 });
	layer.value = new Konva.Layer({ draggable: true });

	text.value = new Konva.Text({
		x: 0,
		y: 0,
		fontSize: 20,
		fill: 'red',
	});
	layer.value.add(text.value);

	circle.value = new Konva.Circle({
		x: stage.value.width() / 2,
		y: stage.value.height() / 2,
		radius: 70,
		fill: '#adf',
		stroke: 'black',
		strokeWidth: 4,
		listening: false,
		strokeScaleEnabled: false,
		scaleX: 2,
	});
	circle.value?.on('mouseover', function () {
		text.value?.text('鼠标经过');
	});
	circle.value?.on('mouseout', function () {
		text.value?.text('鼠标移出');
	});
	layer.value.add(circle.value);

	stage.value.add(layer.value);

	zoomed();
};

/**
 * * 开始监听
 */
const onStartListening = () => {
	circle.value?.listening(true);
	layer.value?.drawHit();
};

/**
 * * 移出监听
 */
const onRemoveListening = () => {
	circle.value?.listening(false);
	layer.value?.drawHit();
};

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

<template>
	<div class="container position-absolute start-0 top-6 z-1">
		<button class="btn btn-primary" type="button" @click="onStartListening">开始监听</button>
		<button class="btn btn-danger" type="button" @click="onRemoveListening">移出监听</button>
	</div>
	<div id="container"></div>
</template>

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