Search code examples
javascriptjquerycsscanvashtml2canvas

How to resize html2canvas and scale to original 100% resolution?


html2canvas(document.querySelector("#capture")).then(canvas => {
    document.querySelector(".canvas-layout").appendChild(canvas);
});

I need to resize this canvas (2304x1440 pixels to 230.4x144, for example) and scale back to the original 100% (2304x1440). How can I do that?

I use it for blur-effect on a background of the fixed header. Then scroll it with $(this).scrollTop(); The method is here.


Solution

  • After you get the canvas object from the html2canvas method, use its context to draw the canvas again in your desired resolution.

    Like this for example,

    function resizeCanvas(canvas, newHeight, newWidth)
    {
            const context = canvas.getContext('2d');
            const imageData = context.getImageData(0, 0, canvas.width, canvas.width);
            const newCanvas = document.createElement("canvas");
            newCanvas.height = canvas.height;
            newCanvas.width = canvas.width;
            const newCanvasContext = newCanvas.getContext('2d');
            newCanvasContext.putImageData(imageData, 0, 0, 0, 0, newWidth, newHeight);
            return newCanvas;
    }