konva-demo/src/views/select/basic/index.vue

86 lines
2.2 KiB
Vue
Raw Normal View History

2024-07-25 10:39:54 +08:00
<script lang="ts" setup>
2024-07-23 08:26:43 +08:00
import { onMounted, ref } from 'vue';
import { useEventListener, useWindowSize } from '@vueuse/core';
2024-07-12 15:57:09 +08:00
import Konva from 'konva/lib';
2024-07-23 08:26:43 +08:00
import { rect1, rect2, selectionRectangle } from '@/views/select/basic/rect.ts';
import { stageEvent } from '@/views/select/basic/stageEvent.ts';
import { drawLine } from '@/views/select/basic/line.ts';
import { Stage } from 'konva/lib/Stage';
import { Layer } from 'konva/lib/Layer';
2024-07-12 15:57:09 +08:00
const { width, height } = useWindowSize();
2024-07-23 08:26:43 +08:00
const stage = ref<Stage>();
const layer = ref<Layer>();
const tr = ref();
2024-07-25 10:39:54 +08:00
const SCALE_BY = 1.1;
const zoomed = () => {
stage.value?.on('wheel', ev => {
2024-07-25 14:07:47 +08:00
// 平台不存在直接返回
2024-07-25 10:39:54 +08:00
if (!stage.value) return;
// 之前缩放比例
const scaleX = stage.value?.scaleX();
const scaleY = stage.value?.scaleY();
2024-07-25 14:07:47 +08:00
// 记录当前鼠标位置
2024-07-25 10:39:54 +08:00
const pointer = stage.value?.getPointerPosition();
2024-07-25 14:07:47 +08:00
// 鼠标在画布的平移量,除以缩放比例得到,鼠标在未缩放时的坐标
2024-07-25 10:39:54 +08:00
const mousePointTo = {
x: (pointer!.x - stage.value?.x()) / scaleX,
y: (pointer!.y - stage.value?.y()) / scaleY,
};
// 判断鼠标滚轮向上还是向下
const direction = ev.evt.deltaY > 0 ? -1 : 1;
2024-07-25 14:07:47 +08:00
// 设置新的缩放比例
2024-07-25 10:39:54 +08:00
const x = direction > 0 ? scaleX * SCALE_BY : scaleX / SCALE_BY;
const y = direction > 0 ? scaleY * SCALE_BY : scaleY / SCALE_BY;
stage.value?.scale({ x, y });
2024-07-25 14:07:47 +08:00
// 设置新的鼠标位置,缩放时保持不变
2024-07-25 10:39:54 +08:00
const position = {
x: pointer!.x - mousePointTo.x * x,
y: pointer!.y - mousePointTo.y * y,
};
stage.value?.position(position);
});
};
2024-07-12 15:57:09 +08:00
const initial = () => {
2024-07-23 08:26:43 +08:00
stage.value = new Konva.Stage({ container: 'container', width: width.value, height: height.value });
layer.value = new Konva.Layer();
stage.value.add(layer.value);
2024-07-12 15:57:09 +08:00
2024-07-23 08:26:43 +08:00
drawLine(stage.value, layer.value);
2024-07-12 15:57:09 +08:00
2024-07-23 08:26:43 +08:00
rect1(layer.value);
rect2(layer.value);
2024-07-12 15:57:09 +08:00
// 添加缩放
2024-07-23 08:26:43 +08:00
tr.value = new Konva.Transformer();
layer.value.add(tr.value);
2024-07-12 15:57:09 +08:00
2024-07-23 08:26:43 +08:00
stageEvent(stage.value, selectionRectangle(layer.value), tr.value);
2024-07-12 15:57:09 +08:00
};
onMounted(() => {
initial();
2024-07-23 08:26:43 +08:00
useEventListener(window, 'resize', function () {
stage.value?.width(width.value);
stage.value?.height(height.value);
// tr.value.forceUpdate();
});
2024-07-25 10:39:54 +08:00
zoomed();
2024-07-12 15:57:09 +08:00
});
</script>
<template>
<div id="container"></div>
</template>