Created
August 19, 2016 03:20
-
-
Save yig/487c3fdff85865d26d1d8b5c8132c023 to your computer and use it in GitHub Desktop.
How to save the contents of <canvas> tags to disk as PNG's with filenames
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Depends on: | |
// Blob: http://purl.eligrey.com/github/Blob.js/blob/master/Blob.js | |
// canvas.toBlobHD: http://purl.eligrey.com/github/canvas-toBlob.js/blob/master/canvas-toBlob.js | |
function saveScreenshot( filename ) | |
{ | |
/// Open in a new window. | |
// var kMIMEType = "image/png"; | |
// var dataURL = renderer.domElement.toDataURL( kMIMEType ); | |
// window.open( dataURL ); | |
blobPNGFromCanvas( | |
renderer.domElement, // replace this with your canvas element | |
function( blob ) { saveAs( blob, filename ); } | |
); | |
} | |
function blobPNGFromCanvas( canvas, callback ) { | |
/* | |
Creates a Blob `blob` from the canvas object `canvas` and calls the function | |
`callback( blob )` afterwards. | |
*/ | |
var kMIMEType = "image/png"; | |
// .toBlobHD is better than .toDataURL( kMIMEType ) | |
var blob = canvas.toBlobHD( callback, kMIMEType ); | |
/* | |
NOTE: In order to be able to save screenshots, you need to create the WebGLRenderer() | |
with preserveDrawingBuffer: true. For example: | |
renderer = new THREE.WebGLRenderer( { | |
// antialias false makes it easy to segment objects in screenshots. | |
antialias: false, | |
// This is necessary for saving screenshots with .toDataURL("image/png") | |
preserveDrawingBuffer: true | |
} ); | |
*/ | |
} | |
// From Gist: https://gist.github.com/yig/aeeb1ee67a13bea98f3d | |
function saveAs( blob, name ) { | |
"use strict"; | |
// Inspired by Syntax: http://stackoverflow.com/questions/23451726/saving-binary-data-as-file-using-javascript-from-a-browser/23451803#23451803 | |
// Initially created to work around a bug in eligray/FileSaver.js | |
// which prevented saving multiple files | |
// (Issue 165: https://github.com/eligrey/FileSaver.js/issues/165 ). | |
// Create a hidden `a` element. | |
var a = document.createElement("a"); | |
document.body.appendChild(a); | |
a.style.cssText = "display: none"; | |
// createObjectURL() will leak memory. | |
var url = window.URL.createObjectURL(blob); | |
a.href = url; | |
a.download = name; | |
a.click(); | |
window.URL.revokeObjectURL(url); | |
a.parentNode.removeChild(a); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment