KonvaJS缩放
缩放效果,当鼠标在图像上,缩放后鼠标不会离开图像的当前位置,根据缩放保持鼠标位置在这个图像上不变
const zoomed = () => {
stage.value?.on('wheel', ev => {
// 平台不存在直接返回
if (!stage.value) return;
// 之前缩放比例
const scaleX = stage.value?.scaleX();
const scaleY = stage.value?.scaleY();
// 记录当前鼠标位置
const pointer = stage.value?.getPointerPosition();
// 鼠标在画布的平移量,除以缩放比例得到,鼠标在未缩放时的坐标
const mousePointTo = {
x: (pointer!.x - stage.value?.x()) / scaleX,
y: (pointer!.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: pointer!.x - mousePointTo.x * x,
y: pointer!.y - mousePointTo.y * y,
};
stage.value?.position(position);
});
};