konva-demo/src/views/shapes/image/index.vue

82 lines
1.8 KiB
Vue

<template>
<div id="container"></div>
</template>
<script lang="ts" setup>
import { Layer } from 'konva/lib/Layer';
import { Image as KonvaImage } from 'konva/lib/shapes/Image';
import { Stage } from 'konva/lib/Stage';
import { nextTick, onMounted, ref } from 'vue';
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 Stage({
container: 'container',
width: 500,
height: 500,
draggable: true,
});
const layer = new Layer({ draggable: true });
zoomed();
const imageObj = new Image();
const konvaImage = new KonvaImage({
x: 50,
y: 5,
image: imageObj,
width: 100,
height: 100,
});
imageObj.src = 'https://konvajs.org/assets/yoda.jpg';
layer.add(konvaImage);
konvaImage.cornerRadius(20);
KonvaImage.fromURL('https://konvajs.org/assets/darth-vader.jpg', function (darthNode) {
darthNode.setAttrs({
x: 50,
y: 160,
scaleX: 0.5,
scaleY: 0.5,
cornerRadius: 20,
});
layer.add(darthNode);
});
stage.value.add(layer);
};
onMounted(() => {
nextTick(() => {
initial();
});
});
</script>