javascript - pdf阅读器中的放大/缩小画布,导致鼠标坐标改变它的位置
问题描述
我目前正在实现一个功能,在 pdf-reader 中将画布放在 pdf 上,以便我们可以在画布上绘制,因此放置画布的 pdf 可以在很大程度上放大和缩小,我必须确保该画布也应该根据 pdf 调整大小,以便在其顶部绘制保持不变,为了调整画布大小,我使用canvas.style.width,drawing.style.height来调整它的大小,当 pdf 调整大小。
但现在我担心的是,在调整鼠标指针大小时会改变它的位置,例如在附加的图像中,由于鼠标坐标的移动,我的鼠标位于右下角并且它绘制在左上角。
我正在使用 RxJS 进行绘图和捕获事件,但总的来说我无法弄清楚如何处理鼠标位置,我希望根据画布调整大小来缩放坐标。
private captureEvents(canvasEl: HTMLCanvasElement) {
// this will capture all mousedown events from the canvas element
this.drawingSubscription = fromEvent(canvasEl, 'mousedown')
.pipe(
switchMap((e) => {
// after a mouse down, we'll record all mouse moves
return fromEvent(canvasEl, 'mousemove')
.pipe(
// we'll stop (and unsubscribe) once the user releases the mouse
// this will trigger a 'mouseup' event
takeUntil(fromEvent(canvasEl, 'mouseup').do((event: WheelEvent) => {
console.log('e', e.type, e);
const prevPos = {
x: null,
y: null
};
this.coordinatesArray[this.file.current_slide - 1].push(prevPos);
console.log('coordinatesArray', this.coordinatesArray);
})),
// we'll also stop (and unsubscribe) once the mouse leaves the canvas (mouseleave event)
takeUntil(fromEvent(canvasEl, 'mouseleave')),
// pairwise lets us get the previous value to draw a line from
// the previous point to the current point
pairwise()
)
})
)
.subscribe((res: [MouseEvent, MouseEvent]) => {
const rect = canvasEl.getBoundingClientRect();
// previous and current position with the offset
const prevPos = {
x: res[0].clientX - rect.left,
y: res[0].clientY - rect.top
};
const currentPos = {
x: res[1].clientX - rect.left,
y: res[1].clientY - rect.top
};
this.coordinatesArray[this.file.current_slide - 1].push(prevPos);
// console.log('coordinatesArray', this.coordinatesArray);
this.drawOnCanvas(prevPos, currentPos);
});
}
此外,我不会在每次放大/缩小时生成新画布,我只是根据它所在页面的尺寸修改它的高度/宽度。
解决方案
在花了很多时间后,我最终解决了它。我已经在相关线程中发布了答案,这将有助于其他遇到类似问题的人。
推荐阅读
- angular - Angular 2+ 如何使用变量值来调用指令?
- acumatica - UseLegacyUI 设置不起作用
- python - 在列表列表中查找出现在两个列表中的元素
- linux - 如何获取当前文件夹名称并从bash中的名称中删除字符
- java - 何时以及如何在 Java 中使用“return this”
- rx-java2 - 如何计算 Observable 中的平均值
? - sql - 具有不同计数和分组依据的嵌套选择
- flutter - 你如何摆脱下面的 NoSuchMethodError
- java - java SpringBoot jar 在 CentOS 上崩溃
- python - 使用 py2neo neo4j 更新属性关系