<script setup lang="ts">
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';

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

const initial = () => {
	const stage = 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.width() / 2,
		y: stage.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.add(layer.value);
};

/**
 * * 开始监听
 */
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 type="button" class="btn btn-primary" @click="onStartListening">开始监听</button>
		<button type="button" class="btn btn-danger" @click="onRemoveListening">移出监听</button>
	</div>
	<div id="container"></div>
</template>

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