optimize: ♻️ horizontal-vertical添加鼠标缩放

This commit is contained in:
Bunny 2024-07-25 00:01:04 +08:00
parent d7434d70e7
commit a29fb2bffa
2 changed files with 45 additions and 6 deletions

View File

@ -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;

View File

@ -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();
// XY
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>