Maison > Questions et réponses > le corps du texte
var type = 'png'; var canvas = document.createElement('canvas'); var imgData = canvas.toDataURL(type); var _fixType = function(type) { type = type.toLowerCase().replace(/jpg/i, 'jpeg'); var r = type.match(/png|jpeg|bmp|gif/)[0]; return 'image/' + r; }; imgData = imgData.replace(_fixType(type), 'image/octet-stream'); var saveFile = function(data, filename) { var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a'); save_link.href = data; save_link.download = filename; var event = document.createEvent('MouseEvents'); event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); save_link.dispatchEvent(event); }; var filename = 'weiyin_' + (new Date()).getTime() + '.' + type; saveFile(imgData, filename);
为什么我最后下载出来的png是空白的呢
欧阳克2016-11-17 15:42:25
其实这个问题出现在var canvas = document.createElement('canvas');这句上面,获取是为空,所以换了 var canvas = document.getElementById('canvas')就可以了
三叔2016-11-17 15:42:08
你把
var imgData = canvas.toDataURL(type);
这句放在获取_fixType后面,并传一个_fixType进去再试试
var fixType = _fixType(type); var imgData = canvas.toDataURL(fixType); imgData = imgData.replace(fixType, 'image/octet-stream');
var canvas = document.createElement('canvas');
这句代码的意思,新创建一个空白canvas元素,所以后面获取到的base64图片也应该是空白的。所以最后就获取了空白了的图片