canvas实现一键下载图片

  • Post author:
  • Post category:其他


下载图片可以使用a标签的download属性,a标签的href设置想要下载的图片路径

<a href="" id="download" download=""></a>

canvas转base64

var canvas = document.getElementById('canvas'),
    ctx = canvas.getContext('2d')
var imgBG = new Image()
imgBG.setAttribute('crossOrigin', 'anonymous'); //设置允许跨域访问
imgBG.src = '../img/printBG.jpg'
imgBG.onload = function () {
    canvas.width = imgBG.width
    canvas.height = imgBG.height
    ctx.drawImage(imgBG,0,0,imgBG.width,imgBG.height)
    var base = canvas.toDataURL('image/png')
    document.getElementById('download').setAttribute('href',base)
    document.getElementById('download').click()
}

有时候base64长度太长会导致a标签的href属性失效,使用canvas的toBlob方法 和 URL.createObjectURL()

canvas.toBlob(function (blob) {
    var url = URL.createObjectURL(blob)
    document.getElementById('download').setAttribute('href',url)
    document.getElementById('download').click()
})



版权声明:本文为yinuoqingqin原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。