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

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

const zoomed = () => {
	stage.value?.on('wheel', ev => {
		if (!stage.value) {
			return;
		}

		// 之前缩放比例
		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 });
	const layer = new Konva.Layer();
	stage.value.add(layer);

	const group = new Konva.Group();
	layer.add(group);

	circle.value = new Konva.Circle({
		x: 70,
		y: 70,
		fill: 'red',
		radius: 30,
	});
	group.add(circle.value);

	const blackRect = new Konva.Rect({
		x: 20,
		y: 20,
		fill: 'black',
		width: 100,
		height: 100,
	});

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

/**
 * * 将圆形zIndex设置为1
 */
const updateCircle = () => {
	circle.value!.zIndex(1);
};

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

<template>
	<div class="container-fluid">
		<button class="btn btn-primary" @click="updateCircle">将圆形zIndex设置为1</button>
		<div id="container"></div>
	</div>
</template>

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