保存 dom/html 为图片

保存 dom/html 为图片

  • 可以使用 html2canvas + canvas2image
  • 或者使用 dom-to-image
  • 或者使用 html-to-image
<script src="https://unpkg.com/html2canvas@1.0.0-rc.5/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">`dom 转图片`</script>
<div id="root">一些文本</div>
// 貌似不支持 iframe => https://github.com/bubkoo/html-to-image/issues/36
const node = document.getElementById(`root`)

{ // 保存图片方法1 node=>canvas=>image
  html2canvas(node).then(function(canvas) {
    document.body.appendChild(canvas);
    Canvas2Image.saveAsImage(document.querySelector(`canvas`), canvas.width, canvas.height, `png`, `test`)
  });
}

{ // 保存图片方法2  node=>image
  // const scale = 1200 / node.offsetWidth; // 生成固定宽度的图像
  const scale = 1.5;
  domtoimage.toPng(node, {
  height: node.offsetHeight * scale,
  width: node.offsetWidth * scale,
  style: {
  transform: "scale(" + scale + ")",
  transformOrigin: "top left",
  width: node.offsetWidth + "px",
  height: node.offsetHeight + "px"
  }}).then(function (dataUrl) {
      var link = document.createElement('a');
      link.download = 'my-image-name.png';
      link.href = dataUrl;
      link.click();
  });
}

{ // 保存图片到剪贴板
  domtoimage.toBlob(node).then(async function (blob) {
    try {
      await navigator.clipboard.write([
        new ClipboardItem({
          [blob.type]: blob
        })
      ]);
      console.log('Image copied.');
    } catch(err) {
      console.error(err.name, err.message);
    }
  });
}
posted @ 2020-04-15 11:22  程序媛李李李李蕾  阅读(668)  评论(0编辑  收藏  举报