首页 > 解决方案 > pdf阅读器中的放大/缩小画布,导致鼠标坐标改变它的位置

问题描述

我目前正在实现一个功能,在 pdf-reader 中将画布放在 pdf 上,以便我们可以在画布上绘制,因此放置画布的 pdf 可以在很大程度上放大和缩小,我必须确保该画布也应该根据 pdf 调整大小,以便在其顶部绘制保持不变,为了调整画布大小,我使用canvas.style.widthdrawing.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);
      });
  } 

此外,我不会在每次放大/缩小时生成新画布,我只是根据它所在页面的尺寸修改它的高度/宽度。

在此处输入图像描述

标签: javascriptangularcanvasrxjshtml5-canvas

解决方案


在花了很多时间后,我最终解决了它。我已经在相关线程中发布了答案,这将有助于其他遇到类似问题的人。

https://stackoverflow.com/a/56363476/5763627


推荐阅读