将canvas作为图片下载

Posted 月岛蘑菇

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将canvas作为图片下载相关的知识,希望对你有一定的参考价值。

将canvas作为图片下载

思路是将canvas转化为base64链接,通过模拟a标签的download属性进行下载

// https://stackoverflow.com/questions/18480474/how-to-save-an-image-from-canvas
function download(canvas, filename) {
  var lnk = document.createElement(\'a\'), e
  lnk.download = filename
  lnk.href = canvas.toDataURL(\'image/png;base64\')

  if(document.createEvent) {
    e = document.createEvent(\'MouseEvents\')
    e.initMouseEvent(\'click\', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null )
    lnk.dispatchEvent(e)
  } else if(lnk.fireEvent) {
    lnk.fireEvent(\'onclick\')
  }
}

放一个html的Demo

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Download Cavans</title>
  <style>
    *{
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    html,body{
      height: 100%;
      width: 100%;
    }
    .wrapper{
      width: 100%;
      height: 100%;
      padding: 100px;
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      align-items: center;
    }
    .button{
      width: 100px;
      height: 40px;
      display: flex;
      justify-content: center;
      align-items: center;
      border: 1px solid #ddd;
      box-shadow: 2px 2px 14px #333;
      cursor: pointer;
      user-select: none;
      transition: all .3s;
    }
    .button:hover{
      transform: skew(-15deg);
    }
  </style>
</head>
<body>
  <div class="wrapper">
    <div class="button">Download</div>
  </div>
  <script>
    var wrapper = document.querySelector(\'.wrapper\')
    var canvas = document.createElement(\'canvas\')
    canvas.width = 500
    canvas.height = 500
    var ctx = canvas.getContext(\'2d\')
    ctx.fillStyle = \'rgba(0, 0, 225, .6)\'
    ctx.fillRect(0, 0, 500, 500)
    ctx.fillStyle = \'rgba(225, 0, 0, .6)\'
    ctx.font = \'600 40px Arial\'
    ctx.fillText(\'Canvas\', 100, 100)
    wrapper.appendChild(canvas)

    function download(canvas, filename) {
      var lnk = document.createElement(\'a\'), e
      lnk.download = filename

      lnk.href = canvas.toDataURL(\'image/png;base64\')

      if(document.createEvent) {
        e = document.createEvent(\'MouseEvents\')
        e.initMouseEvent(\'click\', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null )
        lnk.dispatchEvent(e)
      } else if(lnk.fireEvent) {
        lnk.fireEvent(\'onclick\')
      }
    }

    document.querySelector(\'.button\').onclick = () => {
      download(canvas, \'image.png\')
    }
  </script>
</body>
</html>

以上是关于将canvas作为图片下载的主要内容,如果未能解决你的问题,请参考以下文章

小程序各种功能代码片段整理---持续更新

使用fabric js canvas作为threejs 3d模型纹理

canvas(五) 使用图像

自己定义View时,用到Paint Canvas的一些温故,简单的帧动画(动画一 ,&quot;掏粪男孩Gif&quot;顺便再提提onWindowFocusChanged)(代码片段

微信小程序海报 uniapp

微信小程序海报 uniapp