Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML Canvas vs Image Memory Usage

If I create a canvas element via:

var canvas = document.createElement('canvas');

And then draw to it. If I then keep a reference to that canvas will that use more memory than converting the canvas content to a data url and creating an image element with that data and releasing the reference to the canvas?

Which is less memory consuming? A canvas element or an image element, both the same dimensions with the same image data?

like image 610
Rob Evans Avatar asked Jun 26 '26 21:06

Rob Evans


1 Answers

Using this html test page:

<html>
    <head>
        <script type="text/javascript">
            window.onload = function () {
                var c = document.getElementById("canvas");
                var ctx = c.getContext("2d");
                var img = new Image;
                img.src = "http://blog.buzzbuzzhome.com/wp-content/uploads/2012/06/Canadian-Flag-canada-729711_1280_1024.jpg";
                ctx.drawImage(img, 0, 0);
            }
        </script>
    </head>
    <body>
        <canvas id="canvas" width="1280" height="1024"></canvas>
        <img src="http://blog.buzzbuzzhome.com/wp-content/uploads/2012/06/Canadian-Flag-canada-729711_1280_1024.jpg">
    </body>
</html>

The memory output from a Google Chrome profile snapshot is as follows:

Google Chrome -> Developer Tools -> Profiles -> Take Head Snapshot -> Class Filter:HTML

Google Chrome -> Developer Tools -> Profiles -> Take Head Snapshot -> Class Filter:HTML

The canvas has a smaller retained size (132 to 152 of the img), but a look into what's left over from rendering the image reveals more:

Class Filter:canvas

Class Filter:canvas

IMHO you're going to pay an overhead for rendering to the canvas in most major browsers.

Whether the mess gets cleaned up when your reference is released and your final memory usage is lower is anyone's guess.

I realize I didn't do it strictly the way you intended, but I felt a side by side comparison would give you some idea what's involved.

I suppose if loading the image via canvas is the only way to go, perhaps you're performing some manipulation before outputting the final result, then leaving it in the canvas and attempting to nullify all references for garbage collection will be slightly less expensive for the client.

This test was only done in Google Chrome and I cannot verify anything for other browsers.

Try it yourself!

like image 127
mattdlockyer Avatar answered Jun 30 '26 00:06

mattdlockyer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!