如果我通过以下方式创建画布元素:
var canvas = document.createElement('canvas');
然后吸引它。然后,如果我保留对该画布的引用,是否会比将画布内容转换为数据 url 并使用该数据创建图像元素并释放对画布的引用使用更多的内存?
哪个内存消耗少?画布元素或图像元素,具有相同图像数据的相同尺寸?
如果我通过以下方式创建画布元素:
var canvas = document.createElement('canvas');
然后吸引它。然后,如果我保留对该画布的引用,是否会比将画布内容转换为数据 url 并使用该数据创建图像元素并释放对画布的引用使用更多的内存?
哪个内存消耗少?画布元素或图像元素,具有相同图像数据的相同尺寸?
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
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
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!