当内存被大量变量填满时,canvas变得很慢

问题描述 投票:0回答:0

我的想法是将 imageData 保存到数组(toDataUrl 给出一些带有画布阴影的工件)。但是后来我看到以这种方式存储它会使绘图变得非常慢。特别是在使用像模糊这样的画布滤镜时。很明显,它们会减慢绘图速度,但内存中是否有变量之间的差异是巨大的,而且当我使用像模糊这样的画布时,差异也更大。另外,当我向数组添加例如 100 步时的效果似乎与 2 步没有太大区别

是因为滤镜和模糊之类的画布东西需要大量内存吗?我的问题是:我怎样才能以正确的方式解决这个问题,这样它就不会滞后于画布?

我在 codesandbox 中创建了演示:https://codesandbox.io/s/black-voice-v5oxhw?file=/src/index.js.

这也是代码。当您按下“填充历史记录”按钮时,绘图应该变得非常慢。

import "./styles.css";

const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");

canvas.width = 1000;
canvas.height = 1000;
canvas.style.width = "1000px";
canvas.style.height = "1000px";

const drawButton = document.querySelector(".draw");
const fillHistoryButton = document.querySelector(".fillHistory");

const history = [];

const draw = () => {
  ctx.filter = "blur(5px)";
  for (let i = 0; i < 200; i++) {
    ctx.beginPath();
    console.log(i);
    ctx.arc(
      canvas.width * Math.random(),
      canvas.height * Math.random(),
      4,
      0,
      2 * Math.PI
    );
    ctx.fill();
  }
};

const fillHistory = () => {
  for (let i = 0; i < 2; i++) {
    console.log(i, "adding to history");
    history.push(ctx.getImageData(0, 0, canvas.width, canvas.height));
  }
};

drawButton.addEventListener("click", draw);
fillHistoryButton.addEventListener("click", fillHistory);
javascript html5-canvas
© www.soinside.com 2019 - 2024. All rights reserved.