保存 html 为图片

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="http://html2canvas.hertzen.com/dist/html2canvas.js"></script>
  <script src="https://www.jqueryscript.net/demo/Capture-HTML-Elements-Screenshot/canvas2image.js"></script>
  <script src="https://unpkg.com/dom-to-image@2.6.0/dist/dom-to-image.min.js"></script>
</head>
<body>
  <div id="capture" style="padding: 10px; background: #f5da55">
      <h4 style="color: #000; ">Hello world!</h4>
  </div>
  <button id="save" onclick="save();">保存图片</button>
  <script>
    function save() {
      // Canvas2Image.saveAsImage(document.querySelector(`canvas`), 1200, 148, `png`, `test.png`)

      domtoimage.toJpeg(capture, { quality: 0.95 })
      .then(function (dataUrl) {
          var link = document.createElement('a');
          link.download = 'my-image-name.jpeg';
          link.href = dataUrl;
          link.click();
      });



    }
    html2canvas(document.body).then(function(canvas) {
      document.body.appendChild(canvas);
    });



  </script>
</body>
</html>
posted @ 2020-07-07 16:34  程序媛李李李李蕾  阅读(813)  评论(0编辑  收藏  举报