HTML5 load a png buffer into a canvas (for streaming purpose)

后端 未结 1 1465
栀梦
栀梦 2021-02-09 20:16

Through a websocket, I retrieve a binary buffer of an image in a PNG format (something like that).

I want to load this PNG buffer into a canvas, and then read the differ

1条回答
  •  无人共我
    2021-02-09 20:32

    You can convert your input buffer to a Blob instead, obtain an URL for it and use that to draw onto the canvas instead:

    function onBinaryMessage(input) {
    
        var blob = new Blob([input], {type: 'image/png'});
        var url = URL.createObjectURL(blob);
        var img = new Image;
    
        img.onload = function() {
            var ctx = document.getElementById("canvas").getContext('2d');
            ctx.drawImage(this, 0, 0);
            URL.revokeObjectURL(url);
        }
        img.src = url;
    }
    

    Just note that this will be asynchronous and you would need to provide a callback-mechanism inside the onload handler (in any case you really need to do that in your own example as well). But you won't have to convert to base64 etc. which is a relative costly operation.

    Also note that URL.createObjectURL is currently experimental.

    0 讨论(0)
提交回复
热议问题