You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Canvas的ctx.restore()方法未按预期生效的问题求助

Canvas的ctx.restore()方法未按预期生效的问题求助

我最近在做一个Canvas交互功能,需求是:先在Canvas上绘制一个矩形,之后每次触发touchmove事件时,在触摸位置画一个圆形,但只保留最后一个圆形。我原本想着用ctx.save()保存好初始只有矩形的画布状态,每次画新圆前用ctx.restore()回到初始状态,这样就能覆盖掉之前的圆形,结果实际运行下来,所有画过的圆形都留在画布上,完全没达到预期效果。实在搞不懂哪里出问题了,麻烦大家帮我看看我的代码!

先看初始化Canvas并绘制矩形的代码:

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;
}

然后是触摸移动的监听函数:

function onTouchMove(e) {
  const x1 = e.changedTouches[0].pageX;
  const y1 = e.changedTouches[0].pageY;

  drawCircle(x1, y1 - 55);
}

最后是绘制圆形的函数:

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

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

有没有大佬能指点一下问题出在哪呀?万分感谢!

备注:内容来源于stack exchange,提问作者jurijus01

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 08:54:29