Skip to content

Instantly share code, notes, and snippets.

@gfcarvalho
Created March 13, 2014 00:47
Show Gist options
  • Save gfcarvalho/9519825 to your computer and use it in GitHub Desktop.
Save gfcarvalho/9519825 to your computer and use it in GitHub Desktop.
Two ways to detect if an image generated via canvas is blank (transparent PNG). (canvas.getImageData vs canvas.toDataURL)
<!doctype html>
<html>
<head>
<title>Check transparent canvas</title>
</head>
<body>
<canvas id='editor' style='border:solid'></canvas>
<canvas id='blank' style='display:none'></canvas>
<script>
canvas = document.getElementById('editor');
blank = document.getElementById('blank');
ctx = canvas.getContext("2d");
w = canvas.offsetWidth;
h = canvas.offsetHeight;
// uses getImageData and compare all pixels
f1 = function() {
var data = ctx.getImageData(0, 0, w, h).data;
for(var i = 0, l = data.length; i < l; i += 4) {
if(data[i + 3] !== 0) {
return false;
}
}
return true;
};
// uses toDataURL and compare just the urls
f2 = function() {
return canvas.toDataURL() === blank.toDataURL();
};
console.log('Return of getImageData method', f1());
console.log('Return of toDataURL method', f2());
</script>
</body>
</html>
@gfcarvalho
Copy link
Author

Based on this thread on stackoverflow: http://stackoverflow.com/q/7991139/2252829

Check this JSPerf test to compare performance between methods: http://jsperf.com/check-transparent-canvas

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment