-2

The idea is that you can paint on the canvas, then store it into a variable and move on with other paintings, etc. Then, if you want, reopen that previously painting on the canvas, from the variable.

There's only one canvas element.

This is how I tried to solve that without a result:

<canvas id="myCanvas" width="500" height="500"></canvas>

-

canvas: HtmlCanvasElement;
ctx1: any;
storedCanvas: HTMLCanvasElement;
ctx2: any;

ngAfterviewInit(){
  this.canvas = <HTMLCanvasElement>document.getElementById('myCanvas');
  this.ctx = this.canvas.getContext("2d");
}

saveCanvas(){
  this.storedCanvas = this.canvas;
}

loadCanvas(){
this.canvas.replaceWith(this.storedCanvas); 
}

Whatever I did after using saveCanvas(), the changes affect storedCanvas as well, e.g.:

1) Draw

2) Save

3) Make some changes without saving

4) Load the canvas, the changes from 3) affected storedCanvas as well, meaning canvas and storedCanvas still identical even after the save.

I assume this is not even close to how you're supposed to store and render a canvas.

Skyan
  • 71
  • 1
  • 6
  • because you still only ever create one canvas... – ASDFGerte Dec 09 '19 at 19:47
  • @ASDFGerte Is it possible to store canvas value into a variable? It won't be a pretty solution if I put multiple canvas elements in HTML. – Skyan Dec 09 '19 at 19:53
  • Take a look here [serialize a canvas](https://konvajs.org/docs/data_and_serialization/Serialize_a_Stage.html) Note: this works for simple canvas. – Bibberty Dec 09 '19 at 19:55
  • Don't misunderstand. You did store your canvas into a variable (and as all javascript objects, by reference). Then you change the canvas. Whether you stored it in a variable or not doesn't matter here, it's still only one canvas, and you change it. For copying a canvas, refer to [any-way-to-clone-html5-canvas-element-with-its-content](https://stackoverflow.com/questions/3318565/any-way-to-clone-html5-canvas-element-with-its-content). – ASDFGerte Dec 09 '19 at 19:55
  • @ASDFGerte Ah, I misunderstood. Thanks for the explanation. – Skyan Dec 09 '19 at 20:49

1 Answers1

0

You create the first canvas in the document, and then get a reference to it like so:

this.canvas = <HTMLCanvasElement>document.getElementById('myCanvas');

Now this.canvas is a reference to your first canvas.

You then copy the same reference to a second variable:

this.storedCanvas = this.canvas

So now this.storedCanvas and this.canvas are the same canvas.

What you need to do is create a second canvas using:

const mySecondCanvas = document.createElement('canvas');
mySecondCanvas.id = "mySecondCanvas";

To see the canvas you'll then need to append it the the document body using:

document.body.appendChild(mySecondCanvas);

Read up about reference types vs value types, as HTMLCanvasElement is a reference type. When you assign it to a second variable, it doesn't copy the whole object, it just copies the reference to the same object.

JMadelaine
  • 2,859
  • 1
  • 12
  • 17