由于前两个答案仅适用于具有 base64 数据的 dataURL,并且由于 href 属性太大,此答案已被与“网络错误”相关的更一般问题引用,因此这是我正在使用的代码:
// must be called in a click handler or some other user action
var download = function(filename, dataUrl) {
var element = document.createElement('a')
var dataBlob = dataURLtoBlob(dataUrl)
element.setAttribute('href', URL.createObjectURL(dataBlob))
element.setAttribute('download', filename)
element.style.display = 'none'
document.body.appendChild(element)
element.click()
var clickHandler;
element.addEventListener('click', clickHandler=function() {
// ..and to wait a frame
requestAnimationFrame(function() {
URL.revokeObjectURL(element.href);
})
element.removeAttribute('href')
element.removeEventListener('click', clickHandler)
})
document.body.removeChild(element)
}
// from Abhinav's answer at https://stackoverflow.com/questions/37135417/download-canvas-as-png-in-fabric-js-giving-network-error/
var dataURLtoBlob = function(dataurl) {
var parts = dataurl.split(','), mime = parts[0].match(/:(.*?);/)[1]
if(parts[0].indexOf('base64') !== -1) {
var bstr = atob(parts[1]), n = bstr.length, u8arr = new Uint8Array(n)
while(n--){
u8arr[n] = bstr.charCodeAt(n)
}
return new Blob([u8arr], {type:mime})
} else {
var raw = decodeURIComponent(parts[1])
return new Blob([raw], {type: mime})
}
}
使用这些函数,您可以将代码更改为:
document.getElementById("downloadPreview").addEventListener('click', function() {
var dataURL = _canvasObject.toDataURL({format: 'png', multiplier: 4})
download("hellowWorld.png", dataURL)
})