Skip to content

Instantly share code, notes, and snippets.

@ruda
Last active October 9, 2017 02:32
Show Gist options
  • Save ruda/7b589e9abfb67fc9332f59b2410e5b45 to your computer and use it in GitHub Desktop.
Save ruda/7b589e9abfb67fc9332f59b2410e5b45 to your computer and use it in GitHub Desktop.
Create PNG and allow download from browser [HTML canvas]
// Rudá Moura <[email protected]>
window.onload = function() {
createPNG('png1', 'red');
createPNG('png2', 'blue');
createPNG('png3', 'green');
createPNG('png4', 'turquoise');
}
function createPNG(name, color) {
var a = document.querySelector('a#' + name);
var canvas = document.querySelector('canvas#' + name);
var ctx = canvas.getContext('2d');
ctx.fillStyle = color;
ctx.fillRect(0, 0, 128, 128);
canvas.onclick = function(event) {
var dataURL = canvas.toDataURL();
a.href = dataURL;
//a.href = dataURL.replace(/^data:image\/[^;]/, 'data:application/octet-stream');
a.download = color + ".png";
}
}
<!DOCTYPE html>
<html>
<head>
<script src=createpng.js></script>
</head>
<body>
<a id="png1" href=""><canvas id="png1" width=128 height=128></canvas></a>
<a id="png2" href=""><canvas id="png2" width=128 height=128></canvas></a>
<a id="png3" href=""><canvas id="png3" width=128 height=128></canvas></a>
<a id="png4" href=""><canvas id="png4" width=128 height=128></canvas></a>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment