在浏览器中显示图像的最快方法是什么?

时间:2023-02-08 21:15:58

Assuming I get binary image data from somewhere (web sockets in my case), what's the fastest way to render them in a web browser?

假设我从某个地方获取二进制图像数据(在我的情况下是Web套接字),在Web浏览器中呈现它们的最快方法是什么?

I came up with this approach using Canvas and Blobs.

我使用Canvas和Blobs想出了这种方法。

    var context = canvas.getContext('2d')
    var img = new Image()

    img.onload = function() {
      context.drawImage(img, 0, 0)
      window.URL.revokeObjectURL(this.src)
    }

    img.src = window.URL.createObjectURL(new Blob([data], {'type': 'image\/jpeg'}))

It's already pretty fast (~3ms - 10ms rendering time vor a full HD jpeg). Is there another (faster) way, maybe without the Image element?

它已经非常快(~3ms - 10ms渲染时间与全高清jpeg)。还有另一种(更快的)方式,可能没有Image元素吗?

edit: yes, this is mad science, but in order to achieve 60fps every ms counts.

编辑:是的,这是疯狂的科学,但为了达到60fps每ms的数量。

1 个解决方案

#1


You could try requestAnimationFrame. Here's a shim from Paul Irish.

您可以尝试requestAnimationFrame。这是Paul Irish的一个垫片。

// shim layer with setTimeout fallback
window.requestAnimationFrame = (function(){
  return  window.requestAnimationFrame       ||
          window.webkitRequestAnimationFrame ||
          window.mozRequestAnimationFrame    ||
          function( callback ){
            window.setTimeout(callback, 1000 / 60);
          };
})();

// ...

img.onload = function() {
    var self = this;
    requestAnimationFrame(function(){
        context.drawImage(self, 0, 0)
        window.URL.revokeObjectURL(self.src)
    });
};

#1


You could try requestAnimationFrame. Here's a shim from Paul Irish.

您可以尝试requestAnimationFrame。这是Paul Irish的一个垫片。

// shim layer with setTimeout fallback
window.requestAnimationFrame = (function(){
  return  window.requestAnimationFrame       ||
          window.webkitRequestAnimationFrame ||
          window.mozRequestAnimationFrame    ||
          function( callback ){
            window.setTimeout(callback, 1000 / 60);
          };
})();

// ...

img.onload = function() {
    var self = this;
    requestAnimationFrame(function(){
        context.drawImage(self, 0, 0)
        window.URL.revokeObjectURL(self.src)
    });
};