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

const { width, height } = useWindowSize();

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

	// 限制横向移动
	const horizontally = new Konva.Rect({
		x: 20,
		y: 20,
		width: 100,
		height: 100,
		fill: 'red',
		draggable: true,
		dragBoundFunc(pos) {
			return {
				x: pos.x,
				y: this.absolutePosition().y,
			};
		},
	});
	layer.add(horizontally);

	const vertically = new Konva.Rect({
		x: 160,
		y: 20,
		width: 100,
		height: 100,
		fill: 'green',
		draggable: true,
		dragBoundFunc(pos) {
			return { x: this.absolutePosition().x, y: pos.y };
		},
	});
	layer.add(vertically);

	stage.add(layer);
};

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

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

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