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是空白的呢
其实这个问题出现在var canvas = document.createElement('canvas');这句上面,获取是为空,所以换了 var canvas = document.getElementById('canvas')就可以了
你把
这句放在获取_fixType后面,并传一个_fixType进去再试试
var canvas = document.createElement('canvas');
这句代码的意思,新创建一个空白canvas元素,所以后面获取到的base64图片也应该是空白的。所以最后就获取了空白了的图片