I have a problem when using html2canvas, i need to download a div so i convert it to canvas, below is my code
const handleDownload = () => {
//custom div need to download
let containerImage = document.createElement('div');
containerImage.style.width = 1080
containerImage.style.height = 1080
for(let i = 0;i < 3;i++){
let tmpDiv = document.createElement('div')
tmpDiv.style.width = 1080
tmpDiv.style.height = 300
tmpDiv.style.background = 'red'
containerImage.appendChild(tmpDiv)
}
document.body.appendChild(containerImage)
downloadImageFromCanvas(containerImage,12,() => console.log('1'))
}
//download image fomr canvas
const downloadImageFromCanvas = (Ref, id,callback) => {
html2canvas(Ref)
.then(async (canvas) => {
const photo = await getImage({ canvas, width: 1360, height: 675 });
const element = document.createElement('a');
const blobUrl = URL.createObjectURL(photo);
element.href = blobUrl;
element.download = `Image ${id}`;
element.click();
callback()
})
.catch((e) => console.log('error', e));
};
//convert canvas to blob
const getImage = async ({
canvas,
width,
height,
mime = 'image/png',
quality = 0.8,
}) => {
return new Promise((resolve) => {
const tmpCanvas = document.createElement('canvas');
tmpCanvas.width = width * 0.99;
tmpCanvas.height = height;
const ctx = tmpCanvas.getContext('2d');
ctx.drawImage(
canvas,
0,
0,
canvas.width,
canvas.height,
0,
0,
width,
height
);
tmpCanvas.toBlob(resolve, mime, quality);
});
};
The issue is i already set the width for the div but i alway get this error
error DOMException: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The image argument is a canvas element with a width or height of 0
Does anyone have a solution for this problem? Thank you