fix: 🧩 画布缩放

This commit is contained in:
Bunny 2024-07-24 23:27:29 +08:00
parent 67c49a26a4
commit 4e3b595694
3 changed files with 48 additions and 11 deletions

View File

@ -1,3 +0,0 @@
{
"recommendations": ["Vue.volar"]
}

View File

@ -1 +1 @@
{"version":1721355798048}
{"version":1721834336660}

View File

@ -2,16 +2,55 @@
<div id="container"></div>
</template>
<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', e => {
if (!stage.value) return;
// 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,
};
//
let direction = e.evt.deltaY > 0 ? -1 : 1;
if (e.evt.ctrlKey) direction = -direction;
// X
const newScaleX = direction > 0 ? oldScaleX * SCALE_BY : oldScaleX / SCALE_BY;
// Y
const newScaleY = direction > 0 ? oldScaleY * SCALE_BY : oldScaleY / SCALE_BY;
stage.value!.scale({ x: newScaleX, y: newScaleY });
const newPos = {
x: pointer!.x - mousePointTo.x * newScaleX,
y: pointer!.y - mousePointTo.y * newScaleY,
};
stage.value!.position(newPos);
});
};
const initial = () => {
const stage = new Konva.Stage({ container: 'container', width: width.value, height: height.value });
const layer = new Konva.Layer({ draggable: true });
stage.value = new Konva.Stage({ container: 'container', width: width.value, height: height.value });
const layer = new Konva.Layer();
//
const text = new Konva.Text({
@ -26,8 +65,8 @@ const initial = () => {
//
const circle = new Konva.Circle({
x: stage.width() / 2,
y: stage.height() / 2,
x: stage.value!.width() / 2,
y: stage.value!.height() / 2,
radius: 70,
fill: 'red',
stroke: 'black',
@ -43,7 +82,8 @@ const initial = () => {
text.text('鼠标离开');
});
stage.add(layer);
zoomed();
stage.value!.add(layer);
};
onMounted(() => {