javascript - requestAnimFrame 被多次执行

标签 javascript opencv requestanimationframe tensorflow.js cancelanimationframe

我有一个情绪检测,使用 openCV.js 进行人脸检测,使用 tensorflow.js 进行情绪分类。当我开始情绪检测时,我调用 requestAnimFrame(myProcessingLogic) 函数并将我的检测逻辑传递给回调参数。我的处理逻辑再次调用 requestAnimFrame(myProcessingLogic)。

当禁用情绪检测时,会设置一个全局变量,然后禁用对 requestAnimFrame 的递归调用。这很好用。

...但是在每次重新激活情绪检测时,都会再次调用 requestAnimFrame 调用。这会导致性能问题。

我尝试将 requestAnimFrame() 返回的 id 保存到全局,以便在检测停止时调用 cancelAnimFrame() 但这似乎没有效果。

第一次调用:

function startVideoProcessing() {
    if (!streaming) {
        console.warn("Please startup your webcam");
        return;
    }

    canvasInput = document.createElement('canvas');
    canvasInput.width = videoWidth;
    canvasInput.height = videoHeight;
    canvasInputCtx = canvasInput.getContext('2d');

    canvasBuffer = document.createElement('canvas');
    canvasBuffer.width = videoWidth;
    canvasBuffer.height = videoHeight;
    canvasBufferCtx = canvasBuffer.getContext('2d');

    srcMat = new cv.Mat(videoHeight, videoWidth, cv.CV_8UC4);
    grayMat = new cv.Mat(videoHeight, videoWidth, cv.CV_8UC1);

    requestAnimId = requestAnimationFrame(processVideo);
}

处理逻辑

function processVideo() {
    if(!streaming) {
        return;
    }

    /*
    logic removed to simplify
    */

    requestAnimId = requestAnimationFrame(processVideo);
}
function stopEmotionTracking() {
    stopCamera();
    cancelAnimationFrame(requestAnimId);
    requestAnimId = null;

}

我查看了 firefox 运行时分析,发现在每次重新激活时都会执行一个额外的函数调用。

Image of runtime analysis

最佳答案

我自己发现了错误。它与上面发布的代码无关。在每次开始情绪跟踪时,我都会向视频元素添加一个 EventListener。另一方面,EventListener 执行了 startVideoProcessing。由于这些事件监听器相互堆叠,因此它们被执行了多次。

对于面临相同问题的任何人,请照顾好您的事件监听器 ;)

关于javascript - requestAnimFrame 被多次执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56921796/

相关文章:

javascript - 将 JSON 重新格式化为数组以便在 AngularJs 中使用时出现问题

javascript - 获取字符串内的indexOf char javascript

javascript - 使用 Sencha 5.0 的 vbox 布局

c++ - DirectX 屏幕捕获和输出为视频

c++ - OpenCV 的 Python 或 C++ 编码之间的性能是否不同?

jquery - 在 Firefox 23.0.1 上使用 Mac 触控板的 iScroll 4 中的滚动错误

javascript - 使用 html5 数据操作和 Angular

c++ - 如何以最快的方法删除那些指定的标签组件

angularjs - 需要将 $timeout 和 $apply 与 requestAnimationFrame 一起使用

javascript - ScriptProcessor onaudioprocess 事件速度是否会受到 setInterval 或 requestAnimationFrame 的影响