optimize: ♻️ horizontal-vertical添加鼠标缩放
This commit is contained in:
parent
d7434d70e7
commit
a29fb2bffa
|
@ -35,7 +35,6 @@ const zoomed = () => {
|
|||
|
||||
// 判断是向上滚动鼠标还是向下滚动鼠标,向下滚动为正。向上滚动为负
|
||||
let direction = e.evt.deltaY > 0 ? -1 : 1;
|
||||
// direction = -direction;
|
||||
|
||||
// 新的缩放比例X轴
|
||||
const newScaleX = direction > 0 ? oldScaleX * SCALE_BY : oldScaleX / SCALE_BY;
|
||||
|
|
|
@ -1,12 +1,51 @@
|
|||
<script setup lang="ts">
|
||||
<script lang="ts" setup>
|
||||
import { useWindowSize } from '@vueuse/core';
|
||||
import { onMounted } from 'vue';
|
||||
import { onMounted, ref } from 'vue';
|
||||
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;
|
||||
if (!ev.evt.ctrlKey) return;
|
||||
ev.evt.preventDefault();
|
||||
|
||||
// 未缩放之前,缩放比例X和Y轴
|
||||
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 = () => {
|
||||
const stage = new Konva.Stage({ container: 'container', width: width.value, height: height.value });
|
||||
stage.value = new Konva.Stage({ container: 'container', width: width.value, height: height.value });
|
||||
const layer = new Konva.Layer({ draggable: true });
|
||||
|
||||
// 限制横向移动
|
||||
|
@ -39,7 +78,8 @@ const initial = () => {
|
|||
});
|
||||
layer.add(vertically);
|
||||
|
||||
stage.add(layer);
|
||||
stage.value.add(layer);
|
||||
zoomed();
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
|
@ -51,4 +91,4 @@ onMounted(() => {
|
|||
<div id="container"></div>
|
||||
</template>
|
||||
|
||||
<style scoped lang="scss"></style>
|
||||
<style lang="scss" scoped></style>
|
||||
|
|
Loading…
Reference in New Issue