记录一下,参数中的stageRef为konva的stage对象,我使用的是vue-konva,故可以使用vue的ref对象进行获取。
js
/**
* 获取鼠标在画布中的位置
* @param stageRef
* @returns
*/
export const getMousePosition = (stageRef: Ref) => {
const stage = stageRef.value.getStage();
const pointerPosition = stage.getPointerPosition();
if (pointerPosition) {
// 获取画布的缩放比例
const scale = stage.scaleX(); // 假设x和y方向缩放比例相同
// 获取画布的拖动位置
const stagePos = stage.position();
// 计算鼠标在原始画布坐标系中的位置
return {
x: (pointerPosition.x - stagePos.x) / scale,
y: (pointerPosition.y - stagePos.y) / scale,
};
}
return null;
};