let canvas = document.createElement('canvas');
canvas.width = 100;
canvas.heigth = 100;
// ...绘图
//1.将canvas转换成base64
let imgBase64 = canvas.toDataURL('image/jpeg', 0.8);
//2.将imgBase64转换Blob
let fileData = convertBase64UrlToBlob(imgBase64);
//3.传到后台
let formData = new FormData();
formData.append('file', fileData);
$.post(url,formData,function(data){
//上传成功后做某些事
});
function convertBase64UrlToBlob(base64){
let bytes=window.atob(urlData.split(',')[1]); //去掉url的头,并转换为byte; base64编解码(btoa编码,atob解码)
//处理异常,将ascii码小于0的转换为大于0
let ab = new ArrayBuffer(bytes.length);
let ia = new Uint8Array(ab);
for (let i = 0; i < bytes.length; i++) {
ia[i] = bytes.charCodeAt(i);
}
return new Blob( [ab] , {type : 'image/png'});
}