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

108 lines
2.2 KiB
Vue

<template>
<div id="container"></div>
</template>
<script lang="ts" setup>
import { useWindowSize } from '@vueuse/core';
import Konva from 'konva/lib';
import { onMounted, ref } from 'vue';
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 pointerPosition = stage.value?.getPointerPosition();
const mousePointTo = {
x: (pointerPosition!.x - stage.value?.x()) / scaleX,
y: (pointerPosition!.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: pointerPosition!.x - mousePointTo.x * x,
y: pointerPosition!.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);
zoomed();
// 绘制形状
const rect = new Konva.Rect({
x: 160,
y: 60,
width: 160,
height: 90,
fill: 'red',
name: 'rect',
stroke: 'black',
draggable: true,
});
layer.add(rect);
// 绘制文字
const text = new Konva.Text({ x: 5, y: 5 });
layer.add(text);
const tr = new Konva.Transformer();
layer.add(tr);
tr.nodes([rect]);
// 发生变化时
rect.on('transformstart', function () {
console.log('变化。。。');
});
// 拖拽移动
rect.on('dragmove', function () {
updateText();
});
rect.on('transform', function () {
updateText();
console.log('transform');
});
rect.on('transformend', function () {
console.log('transform end');
});
function updateText() {
const lines = [
'x: ' + rect.x(),
'y: ' + rect.y(),
'rotation: ' + rect.rotation(),
'width: ' + rect.width(),
'height: ' + rect.height(),
'scaleX: ' + rect.scaleX(),
'scaleY: ' + rect.scaleY(),
];
text.text(lines.join('\n'));
}
};
onMounted(() => {
initial();
});
</script>