pdf阅读器中的放大/缩小画布,导致鼠标坐标更改其位置

时间:2019-05-29 09:15:26

标签: javascript angular canvas rxjs html5-canvas

我目前正在实现在pdf阅读器中将画布放置在pdf上的功能,以便我们可以在画布顶部绘制,因此可以在很大程度上放大和缩小放置画布的pdf,必须确保画布也应按照pdf调整大小,以便在画布上保持原样,为调整画布的大小,我使用的是 canvas.style.width drawing.style。高度,以便在pdf调整大小时进行调整。

但是现在我担心的是,在调整鼠标指针的大小时会更改其位置,例如,在附件图像中,由于鼠标坐标的移动,我的鼠标位于右下角,而绘制在左上角。

enter image description here

我正在使用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);
      });
  } 

此外,我并不是在每次放大/缩小时都生成新的画布,而是根据其顶部页面的尺寸修改其高度/宽度。

enter image description here

1 个答案:

答案 0 :(得分:0)

我花了很多时间终于解决了。 我已在相关主题中发布了答案,这将有助于其他经历类似问题的人。

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