HTML CanvasRenderingContext2D - 如何将线条绘制到当前鼠标位置,删除旧线条,保留照片

时间:2018-01-05 14:25:37

标签: angular html5-canvas

我需要用箭头注释图像。

以下代码添加了照片,然后在mouseDown,mouseMove,mouseUp上绘制线条,但结果是多行。如果有层的概念,我不知道这个问题。

我尝试了CanvasRenderingContext2D.restore()CanvasRenderingContext2D.clearRectclearRect()也会从上下文中删除照片。

This is a jsfiddle example我在JS中需要的确切行为,没有CanvasRenderingContext2D。我没有成功地将它的作用从new fabric.Canvas..

开始

HTML:

<canvas #canvas></canvas>

打字稿:

  @ViewChild('canvas')
  public canvas: ElementRef;

  private canvasNE: HTMLCanvasElement;
  private cx: CanvasRenderingContext2D;
  private imageStor = new Image();

  ... 

  private async configCanvas() {
    this.canvasNE = this.canvas.nativeElement;
    this.cx = this.canvasNE.getContext('2d');

    this.cx.lineWidth = 3;
    this.cx.lineCap = 'round';
    this.cx.strokeStyle = '#000';

    this.imageStor.onload = () => {
      this.canvasNE.width = this.imageStor.width;
      this.canvasNE.height = this.imageStor.height;
      this.cx.drawImage(this.imageStor, 0, 0, this.imageStor.width, this.imageStor.height);
      this.cx.save(); 
      // ^This like likely isn't doing anything needed.
    };

    const mouseDown$ = Observable.fromEvent<MouseEvent>(this.canvasNE, 'mousedown');
    const mouseMove$ = Observable.fromEvent<MouseEvent>(this.canvasNE, 'mousemove');
    const mouseUp$ = Observable.fromEvent<MouseEvent>(this.canvasNE, 'mouseup');

    mouseDown$.subscribe(down => {
      mouseMove$
        .takeUntil(mouseUp$)
        .subscribe((move: MouseEvent) => {              
          // this.cx.clearRect(0, 0, this.canvasNE.width, this.canvasNE.height); 
          // ^This removes the original Image
          // this.cx.restore();
          // ^This was a stab in the dark.  
          this.cx.beginPath();
          this.cx.moveTo(down.offsetX, down.offsetY);
          this.cx.lineTo(move.offsetX, move.offsetY);
          this.cx.stroke();
        });
    });
  }

0 个答案:

没有答案