konva-demo/src/views/event-page/remove-event/index.vue

108 lines
2.5 KiB
Vue

<template>
<div class="container">
<button class="btn btn-primary" type="button" @click="onRemoveEvent">移出事件</button>
</div>
<div id="container"></div>
</template>
<script lang="ts" setup>
import { useWindowSize } from '@vueuse/core';
import { onMounted, ref } from 'vue';
import Konva from 'konva/lib';
import { Text } from 'konva/lib/shapes/Text';
import { Circle } from 'konva/lib/shapes/Circle';
import { Stage } from 'konva/lib/Stage';
const { width, height } = useWindowSize();
const circle = ref<Circle>();
const text = ref<Text>();
const count = ref(0);
const stage = ref<Stage>();
const SCALE_BY = 1.1;
/**
* * 缩放
*/
const zoomed = () => {
stage.value?.on('wheel', ev => {
if (!stage.value) {
return;
}
// 之前缩放比例
const oldScaleX = stage.value?.scaleX();
const oldScaleY = stage.value?.scaleY();
const pointer = stage.value?.getPointerPosition();
const mousePointTo = {
x: (pointer!.x - stage.value?.x()) / oldScaleX,
y: (pointer!.y - stage.value?.y()) / oldScaleY,
};
// 判断鼠标是向上滚动还是向下滚动和
const direction = ev.evt.deltaY > 0 ? -1 : 1;
// 设置新的缩放比例
const newScaleX = direction > 0 ? oldScaleX * SCALE_BY : oldScaleX / SCALE_BY;
const newScaleY = direction > 0 ? oldScaleY * SCALE_BY : oldScaleY / SCALE_BY;
stage.value?.scale({ x: newScaleX, y: newScaleY });
// 设置鼠标位置保持不变
const newPosition = {
x: pointer!.x - mousePointTo.x * newScaleX,
y: pointer!.y - mousePointTo.y * newScaleY,
};
stage.value!.position(newPosition);
});
};
const initial = () => {
stage.value = new Konva.Stage({ container: 'container', width: width.value, height: height.value });
const layer = new Konva.Layer({ draggable: true });
// 添加文字
text.value = new Konva.Text({
x: 10,
y: 10,
fontFamily: 'Calibri',
fontSize: 20,
text: '',
fill: 'black',
});
layer.add(text.value);
// 添加圆形
circle.value = new Konva.Circle({
x: stage.value.width() / 2,
y: stage.value.height() / 2 + 10,
radius: 70,
fill: 'green',
stroke: 'black',
strokeWidth: 4,
duration: 1,
});
layer.add(circle.value);
// 添加事件
circle.value?.on('click', function () {
circle.value?.radius(80);
text.value?.text(`点击了:${count.value}`);
count.value++;
});
stage.value.add(layer);
zoomed();
};
// 移出点击事件
const onRemoveEvent = () => {
circle.value?.off('click');
text.value?.text('移出事件');
};
onMounted(() => {
initial();
});
</script>