繁体   English   中英

Angular:如何撤销canvas绘图?

[英]Angular : How to make undo on canvas drawing?

我正在创建我当前项目中需要的一些绘图工具,根据我的要求绘图工作正常,但我正在尝试创建 UNDO 选项,但它无法正常工作。

单击撤消按钮后,我只需要删除最后绘制的线条。

参考这里的代码

<div style="position : relative">
  <canvas class="roiCanvas" id="canvas" #roiCanvas></canvas>

  <button (click)="clear()">Clear</button>
  <button (click)="undo()">Undo</button>
</div>

Angular 撤消代码:

 drawPaths() {
    // delete everything
    this.cx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
    // draw all the paths in the paths array
    this.lineTo.forEach((path: any) => {
      this.cx.beginPath();
      var last = this.lineTo[this.lineTo.length - 1];
      this.cx.moveTo(last.x, last.y);
      for (let i = 1; i < path.length; i++) {
        this.drawChart(path[i].x, path[i].y);
        this.cx.lineTo(path[i].x, path[i].y);
      }
      this.cx.strokeStyle = '#0652DD';
      this.cx.stroke();
    });
  }
  undo() {
    this.lineTo.splice(-1, 1);
    console.log(this.lineTo);
    this.drawPaths();
  }

在此处输入图像描述 请检查下面的 stackblitz 代码库。 https://stackblitz.com/edit/angular-ivy-kdc7dp?file=src/app/app.component.ts

那么你的 drawPaths drawPaths() function 使用的是最后一个 position,当它被删除时它不起作用:

var last = this.lineTo[this.lineTo.length - 1];

所以我重写了撤消 function 以从头到尾画线,现在可以了。

请参阅: https://stackblitz.com/edit/angular-ivy-kdc7dp?file=src/app/app.component.ts

undo() {
  this.lineTo.splice(-1, 1);
  
  this.cx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);

  this.lineTo.forEach((path: any, i: any) => {

    this.cx.beginPath();

    this.drawChart(path.x, path.y);

    if(this.lineTo.length > i+1) {
      this.cx.lineTo(this.lineTo[i+1].x, this.lineTo[i+1].y);
    }

    this.cx.strokeStyle = '#0652DD';
    this.cx.stroke();
  });
}

我会把它留给你去重复代码并让它变得更好;)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM