Skip to content

Instantly share code, notes, and snippets.

@iwek
Created October 23, 2013 20:37
Show Gist options
  • Save iwek/7126242 to your computer and use it in GitHub Desktop.
Save iwek/7126242 to your computer and use it in GitHub Desktop.
Convert CANVAS data to binary data and then to a filename using a Blob
function binaryblob(){
var byteString = atob(document.querySelector("canvas").toDataURL().replace(/^data:image\/(png|jpg);base64,/, ""));
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
var dataView = new DataView(ab);
var blob = new Blob([dataView], {type: "image/png"});
var DOMURL = self.URL || self.webkitURL || self;
var newurl = DOMURL.createObjectURL(blob);
var img = '<img src="'+newurl+'">';
d3.select("#img").html(img);
}
@iwek
Copy link
Author

iwek commented Oct 23, 2013

For SVG to Image Conversion: http://techslides.com/save-svg-as-an-image/

@hoangngoclam
Copy link

Can I ask you a question?
What is "ab" mean?

@gotplitz
Copy link

Can I ask you a question?
What is "ab" mean?

I think it was just a mistake, replace ab with byteString

var byteString = atob(document.querySelector("canvas").toDataURL().replace(/^data:image\/(png|jpg);base64,/, "")); var ia = new Uint8Array(byteString); for (var i = 0; i < byteString.length; i++) { ia[i] = byteString.charCodeAt(i);

@tri5tan
Copy link

tri5tan commented May 23, 2023

Can I ask you a question? What is "ab" mean?

I think it means ArrayBuffer, I assumed it was missing this step:

let ab = new ArrayBuffer(byteString.length);

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