将大约 300 张画布图像保存在一个数组中并发送一次进行处理,在 chrome 中崩溃,但在 Firefox 中工作正常

Saving canvas images around 300 in an array and sending it once to process it crashes in chrome but works fine in firefox

本文关键字:处理 工作 崩溃 chrome 一次 Firefox 但在 并发 张画布 图像 保存      更新时间:2023-09-26

我有一个运行画布动画的JS文件。我所做的是创建一个函数来通过toDataURL获取其内容并将该 URL 数据推送到数组。

最后,我发送 ajax 请求来处理该数组并创建其映像。当我在 Firefox 上执行此操作时它工作正常,但是当尝试在 chrome 上执行此操作时,会出现错误消息。

我认为问题是后数据,即数组变得太大以至于崩溃。

function encode_array() {
  var myjson = JSON.stringify(imgg);
  $.post('localhost:82/html5-video-maker/presentation/array_data1', {
    data: my‌json
  }); //
  return;
}
function makevideo() {
  if (anim) {
    if (flag_video == 1) {
      imgg[cnt] = cs.toDataURL();
    } else {
      imgg[cnt] = canvas.toDataURL();
    }
    cnt++;
  } else {
    encode_array(); //
    doRequest(0);
    clearInterval(t);
  }
}
var t = setInterval('makevideo()', 0.0003);

什么时候可以解决这个问题?

你的 JS 有几个问题。

首先:您可能应该使用imgg.push(flag_video == 1 ? cs.toDataURL() : canvas.toDataURL())因为这可能比手动索引更好地优化。

第二:你的数据可能非常庞大。

第三:你为setInterval使用了一个字符串,而不是传递函数setInterval(makevide)

第四:可能是你问题的根源,是你正在使用的时间间隔非常小的 setInterval......这可能是泛滥,并使堆栈过载; 处理 toDataURL 的时间可能超过您计时的间隔。

您可能最好使用setImmediatesetTimeout(fn,0);

var nextms = new Date().getTime();
function makevideo(){
  var now = new Date().getTime();
  //no ms have passed
  if (now >= nextms) return setTimeout(makevideo,0);
  nextms = now + 16; //60fps ~= 16.666 ms
  //more than one frame of time has passed, get a frame
  imgg.push(flag_video == 1 ? cs.toDataURL() : canvas.toDataURL());
  //keep going until there are 300 frames of animation
  if (imgg.length < 300) return setTimeout(makevideo,0);
  encode_array();
  doRequest(0);
};

现在,每次迭代的几率都超过 16 毫秒,这应该使您的帧保持至少 16 毫秒的距离。

顺便说一句,如果你正在执行请求动画帧,

那么你可能应该在每个动画帧完成后执行此调用,而不是使用如此粗糙的方法。