96 lines
2.1 KiB
Vue
96 lines
2.1 KiB
Vue
<script lang="ts" setup>
|
|
import { onMounted, ref } from 'vue';
|
|
import { useWindowSize } from '@vueuse/core';
|
|
import Konva from 'konva/lib';
|
|
import { Stage } from 'konva/lib/Stage';
|
|
|
|
const { width, height } = useWindowSize();
|
|
const stage = ref<Stage>();
|
|
const SCALE_BY = 1.1;
|
|
|
|
const zoomed = () => {
|
|
stage.value?.on('wheel', ev => {
|
|
if (!stage.value) return;
|
|
|
|
// 原始缩放比例
|
|
const scaleX = stage.value?.scaleX();
|
|
const scaleY = stage.value?.scaleY();
|
|
|
|
// 当前鼠标位置
|
|
const pointer = stage.value?.getPointerPosition();
|
|
|
|
// 鼠标在画布平移量
|
|
const mousePointTo = {
|
|
x: (pointer!.x - stage.value?.x()) / scaleX,
|
|
y: (pointer!.y - stage.value?.y()) / scaleY,
|
|
};
|
|
|
|
// 判断鼠标是向上滚动还是向下滚动
|
|
const direction = ev.evt.deltaY > 0 ? -1 : 1;
|
|
|
|
// 设置新的缩放比例
|
|
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 });
|
|
|
|
// 设置新的鼠标位置,缩放时保持不变
|
|
const position = {
|
|
x: pointer!.x - mousePointTo.x * x,
|
|
y: pointer!.y - mousePointTo.y * y,
|
|
};
|
|
stage.value?.position(position);
|
|
});
|
|
};
|
|
|
|
const initial = () => {
|
|
stage.value = new Konva.Stage({ container: 'container', width: width.value, height: height.value });
|
|
const layer = new Konva.Layer();
|
|
stage.value.add(layer);
|
|
|
|
const text1 = new Konva.Text({
|
|
x: 50,
|
|
y: 70,
|
|
fontSize: 20,
|
|
text: '不缩放',
|
|
draggable: true,
|
|
});
|
|
layer.add(text1);
|
|
|
|
const text2 = new Konva.Text({
|
|
x: 50,
|
|
y: 180,
|
|
fontSize: 20,
|
|
text: '缩放',
|
|
draggable: true,
|
|
});
|
|
layer.add(text2);
|
|
|
|
const tr1 = new Konva.Transformer({
|
|
nodes: [text1],
|
|
keepRatio: true,
|
|
enabledAnchors: ['top-left', 'top-right', 'bottom-left', 'bottom-right'],
|
|
});
|
|
layer.add(tr1);
|
|
|
|
const tr2 = new Konva.Transformer({
|
|
nodes: [text2],
|
|
keepRatio: false,
|
|
enabledAnchors: ['top-left', 'top-right', 'bottom-left', 'bottom-right'],
|
|
});
|
|
|
|
layer.add(tr2);
|
|
|
|
zoomed();
|
|
};
|
|
|
|
onMounted(() => {
|
|
initial();
|
|
});
|
|
</script>
|
|
|
|
<template>
|
|
<div id="container"></div>
|
|
</template>
|
|
|
|
<style lang="scss" scoped></style>
|