Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

dom-to-image 的使用 #8

Open
JslinSir opened this issue May 17, 2022 · 0 comments
Open

dom-to-image 的使用 #8

JslinSir opened this issue May 17, 2022 · 0 comments
Labels
H5 H5 相关问题

Comments

@JslinSir
Copy link
Owner

介绍

正如官网所描述的那样:dom-to-image 可以将任意dom节点转换为用JavaScript编写的矢量(SVG)或(PNG或JPEG)图像。

使用

  • 可以先把要生成的dom节点 用div高度为0 的 块进行包裹
  • 生成后的图片可以填充到另外一个块中
import domtoimage from 'dom-to-image';
var node = document.getElementById('my-node');

domtoimage.toPng(node)
    .then(function (dataUrl) {
        var img = new Image();
        img.src = dataUrl;
        document.body.appendChild(img);
    })
    .catch(function (error) {
        console.error('oops, something went wrong!', error);
    });

关于失真问题的处理

createImg() {
      Toast.loading({
        duration: 10*1000,
        message: "资料生成中...",
        forbidClick: true
      });
      const node = document.getElementById("sheet-dom-id");
      const scale = window.devicePixelRatio
      console.log("node:", node);
      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(dataUrl => {
          console.log("dataUrl:", dataUrl);
          const img = new Image();
          img.src = dataUrl;
          img.style.width = "100%"
          document.getElementById("sheet-show-container").appendChild(img);
        })
        .catch(function(error) {
          console.error("oops, something went wrong!", error);
        })
        .finally(()=>{
             Toast.clear()
        })
    }

生成后的图片可以 ,设置宽度100%,这样不会出现滚动的情况

@JslinSir JslinSir added the H5 H5 相关问题 label May 17, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
H5 H5 相关问题
Projects
None yet
Development

No branches or pull requests

1 participant