跳到主要内容

相对于指针位置缩放舞台

此示例展示如何实现相对于鼠标指针位置的缩放。这种方式以鼠标指针为中心缩放内容,可以提供更自然的缩放体验。

操作说明: 使用鼠标滚轮或触控板放大和缩小。观察内容如何以指针位置为中心缩放,而不是以舞台中心缩放。

import Konva from 'konva';

const width = window.innerWidth;
const height = window.innerHeight;

const stage = new Konva.Stage({
container: 'container',
width: width,
height: height,
});

const layer = new Konva.Layer();
stage.add(layer);

const circle = new Konva.Circle({
x: stage.width() / 2,
y: stage.height() / 2,
radius: 50,
fill: 'green',
});
layer.add(circle);

const scaleBy = 1.01;
stage.on('wheel', (e) => {
// stop default scrolling
e.evt.preventDefault();

const oldScale = stage.scaleX();
const pointer = stage.getPointerPosition();

const mousePointTo = {
x: (pointer.x - stage.x()) / oldScale,
y: (pointer.y - stage.y()) / oldScale,
};

// how to scale? Zoom in? Or zoom out?
let direction = e.evt.deltaY > 0 ? 1 : -1;

// when we zoom on trackpad, e.evt.ctrlKey is true
// in that case lets revert direction
if (e.evt.ctrlKey) {
direction = -direction;
}

const newScale = direction > 0 ? oldScale * scaleBy : oldScale / scaleBy;

stage.scale({ x: newScale, y: newScale });

const newPos = {
x: pointer.x - mousePointTo.x * newScale,
y: pointer.y - mousePointTo.y * newScale,
};
stage.position(newPos);
});