javascript - Three.js 中的帧速率异常高

标签 javascript reactjs iframe three.js

我启动了this site昨天(一个实时编辑网站 three.js 示例),发现在更新代码或导航到多个示例文件时,帧速率飙升至 1000 f/s 左右。

第一次提到这个是here 。我不确定为什么更新后帧速率会增加。 WebGL Canvas 位于 iframe 内,我使用以下代码更新 iframe 内容(iframe 的 id 为“preview”):

    var previewFrame = document.getElementById('preview');
    var preview = previewFrame.contentDocument || previewFrame.contentWindow.document;
    preview.open();
    preview.write(this.props.code);
    preview.close();

有人知道如何解决这个问题吗?编辑是通过CodeMirror完成的。该网站是用 React 构建的。所有src代码都在repo here中.

最佳答案

我的猜测是您正在启动多个 requestAnimationFrame 循环。

例如

let numLoops = 0;
const countElem = document.querySelector("#count");
const stats = new Stats();
document.body.appendChild(stats.domElement);

function loop() {
  stats.update();
  
  requestAnimationFrame(loop);
}

function startLoop() {
  ++numLoops;
  countElem.textContent = numLoops;
  requestAnimationFrame(loop);
}

startLoop();

document.querySelector("button").addEventListener('click', startLoop);
<script src="https://cdnjs.cloudflare.com/ajax/libs/stats.js/r16/Stats.min.js"></script>
<button>Click to add another requestAnimationFrame loop</button>
<div>Num Loops Running: <span id="count"></span></div>

我使示例可编辑并可在 http://webglfundamentals.org 上运行的方式是使用 blob 在 iframe 中运行示例。每当用户选择“更新”时,我都会使用其编辑的源生成一个新的 blob,然后将 iframe 设置为该新 blob 的 URL。这意味着示例将完全重新加载,因此任何旧代码/循环/事件/webgl 上下文等都会被浏览器丢弃。

您可以看到the code here这实际上是

function runLastVersionOfUsersCode() {
  var url = getSourceBlob(usersEditedHtml);
  someIFrameElement.src = url;
}

var blobUrl;
function getSourceBlob(options, htmlForIFrame) {
  // if we already did this discard the old one otherwise
  // it will stick around wasting memory
  if (blobUrl) {
    URL.revokeObjectURL(blobUrl);
  }

  var blob = new Blob([htmlForIFrame], {type: 'text/html'});
  blobUrl = URL.createObjectURL(blob);
  return blobUrl;
}

如果你看actual code for getSourceBlob您会发现它做了更多的工作,但基本上就是上面的内容。

关于javascript - Three.js 中的帧速率异常高,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41383107/

相关文章:

javascript - 在地址栏中显示 iFrame url

javascript/lodash : how to do a recursive deep get in an object thanks to a sub tree object

javascript - CustomListItem 中没有事件触发

javascript - 从外部 API 为 React 组件绑定(bind)数据

reactjs - React.js 应用程序使用 Google 登录,错误 "idpiframe_initialization_failed"

html - 在 iframe 中覆盖/自定义 css

javascript - 如何在 AngularJs 中注入(inject)模块的 2 个不同实例

reactjs - 类型 'boolean' 不可分配给类型 'number' .ts

reactjs - 使用 Jest 和 Enzyme 测试基于 ContextAPI 数据的组件的条件渲染

javascript - contentDocument.documentURI 替代IE6和IE7?