So I have a set of nested elements and I want to capture the resulting image to store in the clipboard. dom-to-image
does a great job but it generates the image but the canvas has more space than it is intended to occupy.
const copyImage = () => {
domtoimage.toBlob(document.getElementById("preview"))
.then(blob => {
navigator.clipboard.write([new ClipboardItem({'image/png': blob})])
});
}
Eg:
How to fix this problem?
I found the solution with help from an observation by @cworf on GitHub. His/her observation was, that this issue occurs when the system DPI is higher than 72. Which means window.devicePixelRatio
is different from 1.
So to solve the problem, you should rescale the resulting image as follows.
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})])
});
}