把其他域的图片在canvas中转换为base64时,会遇到跨域安全限制。
目前,唯一可行的方案是,把图片文件以arraybuffer的形式ajax下载下来,然后直接转base4。
但是,这样有个毛病,就是可能会浪费带宽,多下载一次。
/* var getBase64ByUrl = function(src, callback, outputFormat) { var canvas = document.createElement('canvas'), ctx = canvas.getContext('2d'), img = new Image; img.crossOrigin = 'Anonymous'; img.onload = function() { canvas.height = img.height; canvas.width = img.width; ctx.drawImage(img, 0, 0); //默认图片文件的原始size 缩小base串需加第4、5个参数 alert(5) try{ var dataURL = canvas.toDataURL(outputFormat || 'image/png'); } catch(e) { alert(e.name + ": " + e.message); alert(JSON.stringify(e)); } dataURL =dataURL.replace("data:image/png;base64,", ""); //dataURL =encodeURIComponent(dataURL); alert(dataURL); callback(dataURL); canvas = null; }; img.src = src;alert(6.5) }*/ var getBase64ByUrl = function(src, callback, outputFormat) { var xhr = new XMLHttpRequest(); xhr.open('GET', src, true); xhr.responseType = 'arraybuffer'; xhr.onload = function(e) { if (xhr.status == 200) { var uInt8Array = new Uint8Array(xhr.response); var i = uInt8Array.length; var binaryString = new Array(i); while (i--) { binaryString[i] = String.fromCharCode(uInt8Array[i]); } var data = binaryString.join(''); var base64 = window.btoa(data); var dataUrl = "data:" + (outputFormat || "image/png") + ";base64," + base64; alert(dataUrl) callback.call(this, dataUrl); } }; xhr.send(); }
参考
http://stackoverflow.com/questions/22783368/android-browser-only-canvas-todataurl-throws-uncaught-error-securityerror-dom