Angular : How to make undo on canvas drawing?

Angular : How to make undo on canvas drawing?

Problem Description:

I’m creating some drawing tool which is required in my current project, as per my requirement the drawing works fine, but I’m trying to create the UNDO option, and it’s not working properly.

Once the undo button clicks I need to remove the last drawn line only.

Refer the code here

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

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

Angular Code for undo:

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

enter image description here
Please check the below stackblitz codebase.

Solution – 1

Well your drawPaths() function is using the last position, which does not work when this is removed:

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

So i re-wrote the undo function to just draw the lines from start to finish, and this now works.


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

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

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

    if(this.lineTo.length > i+1) {[i+1].x, this.lineTo[i+1].y);
    } = '#0652DD';;

I’ll leave it to you to dedupe the code and make it nice 😉

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.