<script setup lang="ts">
import { nextTick, onBeforeMount, ref } from 'vue';
import { Stage } from 'konva/lib/Stage';
import { Layer } from 'konva/lib/Layer';
import { Sprite } from 'konva/lib/shapes/Sprite';

const blob = ref();
const initial = () => {
	const stage = new Stage({
		width: 500,
		height: 500,
		container: 'container',
	});

	const layer = new Layer({ draggable: true });
	const animations = {
		idle: [
			// x, y, width, height (4 frames)
			2, 2, 70, 119, 71, 2, 74, 119, 146, 2, 81, 119, 226, 2, 76, 119,
		],
		punch: [
			// x, y, width, height (4 frames)
			2, 138, 74, 122, 76, 138, 84, 122, 346, 138, 120, 122,
		],
	};

	const imageObj = new Image();
	imageObj.onload = function () {
		blob.value = new Sprite({
			x: 50,
			y: 50,
			image: imageObj,
			animation: 'idle',
			animations: animations,
			frameRate: 7,
			frameIndex: 0,
		});
		layer.add(blob.value);
		blob.value.start();
	};
	imageObj.src = 'https://konvajs.org/assets/blob-sprite.png';

	stage.add(layer);
};

const onClickImage = () => {
	blob.value.animation('punch');
	blob.value.on('frameIndexChange.button', function () {
		if (blob.value.frameIndex() === 2) {
			setTimeout(function () {
				blob.value.animation('idle');
				blob.value.off('.button');
			}, 1000 / blob.value.frameRate());
		}
	});
};

onBeforeMount(() => {
	nextTick(() => initial());
});
</script>

<template>
	<button class="btn btn-primary" @click="onClickImage">点击</button>
	<div id="container"></div>
</template>

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