所以我有一组嵌套元素,我想捕获生成的图像以存储在剪贴板中。
dom-to-image
做得很好,但它生成了图像,但画布的空间比预期占用的空间多。
const copyImage = () => {
domtoimage.toBlob(document.getElementById("preview"))
.then(blob => {
navigator.clipboard.write([new ClipboardItem({'image/png': blob})])
});
}
例如:
如何解决这个问题?
我在 GitHub 上 @cworf 的观察的帮助下找到了解决方案。他/她的观察是,当系统 DPI 高于 72 时,就会出现此问题。这意味着
window.devicePixelRatio
与 1 不同。
因此,要解决该问题,您应该按如下方式重新缩放生成的图像。
const copyImage = () => {
const el = document.getElementById("preview");
const scale = window.devicePixelRatio;
domtoimage.toBlob(el, {
height: el.offsetHeight * scale,
width: el.offsetWidth * scale,
})
.then(blob => {
navigator.clipboard.write([new ClipboardItem({'image/png': blob})])
});
}