慕森卡
火狐canvas.toblob()和canvas.mozGetAsFile()方法。但其他浏览器没有。我们可以从画布中获取Dataaurl,然后将dataurl转换为BLOB对象。这是我的dataURLtoBlob()功能。很短。function 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});}在FormData中使用此函数处理画布或数据。例如:var dataurl = canvas.toDataURL('image/jpeg',0.8);var blob = dataURLtoBlob(dataurl);var fd = new FormData();
fd.append("myFile", blob, "thumb.jpg");此外,您还可以创建一个HTMLCanvasElement.prototype.toBlob方法用于非壁虎引擎浏览器。if(!HTMLCanvasElement.prototype.toBlob){
HTMLCanvasElement.prototype.toBlob = function(callback, type, encoderOptions){
var dataurl = this.toDataURL(type, encoderOptions);
var bstr = atob(dataurl.split(',')[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
var blob = new Blob([u8arr], {type: type});
callback.call(this, blob);
};}现在canvas.toBlob()适用于所有现代浏览器,而不仅仅是Firefox。例如:canvas.toBlob(
function(blob){
var fd = new FormData();
fd.append("myFile", blob, "thumb.jpg");
//continue do something...
},
'image/jpeg',
0.8);