Saving HTML Element Saves With Blurry Image using html2canvas

So in my inspect element, I have the following

<div id="grid-container"><div style="height: 500px; width: 500px;"><canvas height="10" width="10" style="height: 500px; width: 500px; position: absolute; image-rendering: pixelated;"></canvas><canvas height="500" width="500" style="position: absolute; image-rendering: pixelated;"></canvas></div></div>

This the result on screen
enter image description here

Now I am trying to save that as a png, jpg and svg file. Tried using html2canvas to take a screenshot of that element using following codes

    // Function to download the canvas content as an image
function downloadImage(format) {
    // Get the grid-container element
    const gridContainer = document.getElementById("grid-container");

    // Use html2canvas to capture the grid-container content
    html2canvas(gridContainer).then(function (canvas) {
        // Convert the captured canvas to a data URL
        const imageDataURL = canvas.toDataURL(`image/${format}`);

        // Create a temporary anchor element to trigger the download
        const tempLink = document.createElement("a");
        tempLink.href = imageDataURL;
        tempLink.download = `pixelroyal-${gridContainer.offsetWidth}x${gridContainer.offsetHeight}-download.${format}`;

        // Trigger the download
        tempLink.click();
    });
}

// Event listeners for download buttons
document.getElementById("downloadPNG").addEventListener("click", () => downloadImage("png"));
document.getElementById("downloadJPG").addEventListener("click", () => downloadImage("jpeg"));
document.getElementById("downloadSVG").addEventListener("click", () => downloadImage("svg"));

The issue is it saves a screenshot but the image is blurry as seen below

enter image description here

So not sure what the cause of this is.

  • Why are you using html2canvas instead of using .toDataURL() directly from the original canvas where you drew the figure?

    – 

  • @Pointy I tried using that but the image still shows blurry

    – 

  • Well, I think what’s happening is that you have a canvas with a 10×10 grid, but it is stretched over a 500px square. I bet if you tried with a 10px square you’d get what you expect (except really small), and then put that in an <img> tag at 500px square and you’ll see the same result.

    – 

  • Would love to know how to do that. I tried this but still blurry image “newWindow.document.write(‘<img src=”‘ + imageDataURL + ‘” alt=”Captured Image”/>’);”

    – 




  • learn about interpolation. here: nearest neighbor, linear.

    – 

Leave a Comment