时间:2022-07-09 09:36:55 | 栏目:JavaScript代码 | 点击:次
我们把图像文件的内容直接写在了HTML 文件中,这样做的好处是,节省了一个HTTP 请求。坏处呢,就是浏览器不会缓存这种图像。现在我们提供一个js:
function convertImgToBase64(url, 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); var dataURL = canvas.toDataURL(outputFormat || 'image/png'); callback.call(this, dataURL); canvas = null; }; img.src = url; } convertImgToBase64('http://bit.ly/18g0VNp', function(base64Img){ // Base64DataURL });