SOURCE http://blog.csdn.net/cuixiping/article/details/45932793
Canvas converted to Dataurl (get dataurl from canvas)
var dataurl = canvas.toDataURL(‘image/png‘);var dataurl2 = canvas.toDataURL(‘image/jpeg‘, 0.8);
Convert file object to Dataurl, Blob object to Dataurl
The file object is also a Blob object, with the same processing.
function readBlobAsDataURL(blob, callback) { var a = new FileReader(); a.onload = function(e) {callback(e.target.result);}; a.readAsDataURL(blob);}//example:readBlobAsDataURL(blob, function (dataurl){ console.log(dataurl);});readBlobAsDataURL(file, function (dataurl){ console.log(dataurl);});
Dataurl Convert to Blob object
function Span class= "Hljs-title" >dataurltoblob (dataurl) {var arr = Dataurl.split ( ","), mime = Arr[0].match ( /:(. *); [1], BSTR = Atob (Arr[1]), n = bstr.length, U8arr = new uint8array (n); while (n--) {U8arr[n] = Bstr.charcodeat (n);} return new Blob ([U8arr], {type:mime});} //test:var blob = Dataurltoblob ( data:text/plain;base64,ywfhywfhyq== ')
Dataurl picture data drawn to canvas
The image object is constructed first, SRC is Dataurl, and the picture onload is drawn to the canvas
var img = new Image();img.onload = function(){ canvas.drawImage(img);};img.src = dataurl;
File,blob picture file data is drawn to canvas
Convert to a URL first, then construct the image object, SRC is Dataurl, and the picture onload is drawn to the canvas
Using the Readblobasdataurl function above, the URL of the Dataurl format is obtained from the File,blob object, and then the dataurl image data is drawn to the canvas
function (dataurl){ var img = new Image(); img.onload = function(){ canvas.drawImage(img); }; img.src = dataurl;});
Different methods are used to construct different types of URLs (Dataurl, Objecturl (Bloburl), Filesystemurl, respectively). This is not described here, but only in the case of Dataurl.
Filesystemurl does not refer to the form of a local file URL (file:///...), but rather a URL formatted similar to support for filesystem:http://...
browser support for sandboxed file systems (currently chrome only).
Canvas converted to BLOB object and sent using Ajax
After converting to a BLOB object, you can upload an image file using Ajax.
Get Dataurl from canvas before converting Dataurl to blob object
var dataurl = canvas.toDataURL(‘image/png‘);var blob = dataURLtoBlob(dataurl);//使用ajax发送var fd = new FormData();fd.append("image", blob, "image.png");var xhr = new XMLHttpRequest();xhr.open(‘POST‘, ‘/server‘, true);xhr.send(fd);
Go Dataurl and File,blob,canvas objects convert JavaScript to each other