Last active
December 26, 2016 23:38
-
-
Save cheapsteak/972cc6eb47f5b7472712037627f912aa to your computer and use it in GitHub Desktop.
canvas drawimage hijack
This file contains hidden or 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
| // https://stuk.github.io/jszip/documentation/howto/write_zip.html | |
| // https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.3/FileSaver.min.js | |
| window.getCanvasContext = HTMLCanvasElement.prototype.getContext; | |
| window.imageStacks = [] | |
| let canvasContexts = [] | |
| function registerCanvas(canvas, context) { | |
| cavnasContexts.push({canvas, context}) | |
| } | |
| HTMLCanvasElement.prototype.getContext = function () { | |
| const context = getCanvasContext.apply(this, arguments) | |
| const canvas = this | |
| const imageStack = [] | |
| window.imageStacks.push(imageStack) | |
| const drawImage = context.drawImage | |
| let i = 0 | |
| context.drawImage = function() { | |
| drawImage.apply(this, arguments) | |
| const l = i++ | |
| canvas.toBlob((blob) => {imageStack[l] = blob}, 'image/png') | |
| } | |
| return context | |
| } | |
| function clear () { | |
| imageStacks = [] | |
| } | |
| function blobLatest () { | |
| blobsToImage(imageStacks.slice(-1)[0]) | |
| .then(clear) | |
| } | |
| function blobsToImage (blobs, filename = 'images') { | |
| const zip = new JSZip(); | |
| blobs.forEach((blob, i) => zip.file(`${filename}_${i}.png`, blob)) | |
| return zip | |
| .generateAsync({type: 'blob'}) | |
| .then((blob) => saveAs(blob, `${filename}.zip`)) | |
| } | |
| function loadScripts(srcs) { | |
| let d = document; | |
| return Promise.all(srcs.map((src) => new Promise((resolve, reject) => { | |
| let script = d.createElement('script') | |
| script.type = 'text/javascript' | |
| script.async = true | |
| script.onload = resolve; | |
| script.onerror = reject; | |
| script.src = url; | |
| d.getElementsByTagName('head')[0].appendChild(script); | |
| }))) | |
| } | |
| loadScripts([ | |
| 'https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js', | |
| 'https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.3/FileSaver.min.js', | |
| ]); | |
| // rm anim.gif | |
| // mogrify -format gif *.png; | |
| // gifsicle --colors 256 --delay=10 --unoptimize --disposal=previous --loopcount=1 -O2 *.gif > anim.gif; |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
calling toBlob in the drawImage seems to slow things down
try saving the pixel array via
ctx.getImageData(left, top, width, height), then converting to png as part of the packaging process