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

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

const { width, height } = useWindowSize();

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

	stage.add(layer);

	// 绘制形状
	const rect = new Konva.Rect({
		x: 160,
		y: 60,
		width: 160,
		height: 90,
		fill: 'red',
		name: 'rect',
		stroke: 'black',
		draggable: true,
	});

	layer.add(rect);

	// 绘制文字
	const text = new Konva.Text({ x: 5, y: 5 });
	layer.add(text);

	const tr = new Konva.Transformer();
	layer.add(tr);
	tr.nodes([rect]);

	// 发生变化时
	rect.on('transformstart', function () {
		console.log('变化。。。');
	});

	// 拖拽移动
	rect.on('dragmove', function () {
		updateText();
	});

	rect.on('transform', function () {
		updateText();
		console.log('transform');
	});

	rect.on('transformend', function () {
		console.log('transform end');
	});

	function updateText() {
		const lines = [
			'x: ' + rect.x(),
			'y: ' + rect.y(),
			'rotation: ' + rect.rotation(),
			'width: ' + rect.width(),
			'height: ' + rect.height(),
			'scaleX: ' + rect.scaleX(),
			'scaleY: ' + rect.scaleY(),
		];
		text.text(lines.join('\n'));
	}
};

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