Search code examples
javascripthtml5-canvas

Any idea how to make canvas ctx.restore() to work here?


enter image description hereUsing HTML canvas to draw circles onto rectangle with each "touchmove" event.

Expecting to see the last circle only because using ctx.restore() and also previosly ctx.save() the initial canvas with the rectangle, but seeing all previosly drawn circles instead. Don't know why ctx.restore() isn't happening. Please see the code.

Making canvas and drawing a rectangle

  function drawInitialCanvas(x, y) {
const parent = whatEverYourParent;

if (parent.firstElementChild) {
  parent.firstElementChild.remove();
}

const canvas = document.createElement("canvas");
elemContentStep1.append(canvas);
canvas.setAttribute("id", "myCanvas");
canvas.setAttribute("width", 355);
canvas.setAttribute("height", 650);

const ctx = canvas.getContext("2d");
ctx.strokeStyle = "white";

ctx.rect(20, 500, 300, 100);
ctx.fill();
ctx.save();

crossFadeCanvasCtx = ctx;
 }

the touch listener

  function onTouchMove(e) {

const x1 = e.changedTouches[0].pageX;
const y1 = e.changedTouches[0].pageY;

drawCircle(x1, y1 - 55);
  }

draw circle

  function drawCircle(x, y) {
const ctx = crossFadeCanvasCtx;

ctx.restore();
ctx.beginPath();
ctx.arc(x, y, 30, 0, 2 * Math.PI);
ctx.stroke();
   }

Any ideas very welcome!


Solution

  • ctx.restore() will restore all the attributes of the context that have been saved by a previous call to ctx.save() (and will remove this saved state of the list of states).

    The ctx.save() method will save all the properties you can set on the context, the current transformation matrix, the current clipping path, the current dash list, and that's it. It won't save the current state of the bitmap. So calling ctx.restore() won't change the bitmap content in any way.

    You need to clear the canvas and redraw everything at every frame. To clear the bitmap, use ctx.clearRect(0, 0, canvas.width, canvas.height).