save html page as image using javascript

HTML pages can be saved as images using JavaScript by using the HTML5 canvas element. The canvas element is a HTML element which allows you to draw graphics on a web page using JavaScript. This can be used to capture a screenshot of your HTML page and save it as an image file. To do this, you need to first create a canvas element in your HTML page and set the dimensions of the canvas to the size of the page using JavaScript. You can then use the drawImage() function to draw the HTML page onto the canvas. Once this is done, you can use the toDataURL() function to convert the canvas into an image Data URL. This can then be used to create an image element and set its source to the Data URL. Finally, you can use the download attribute on the image element to save the image onto your local machine. The code for this can be written as follows:


// Create canvas element and set its dimensions
let canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

// Draw the HTML page onto the canvas
let ctx = canvas.getContext('2d');
ctx.drawImage(document.documentElement, 0, 0);

// Convert canvas into Data URL
let dataURL = canvas.toDataURL('image/png');

// Create image element with Data URL as source
let image = document.createElement('img');
image.src = dataURL;

// Set download attribute on the image
image.setAttribute('download', 'page.png');

// Append image to the document
document.body.appendChild(image);

Using the above code, you can save your HTML page as an image file. Additionally, you can also use third-party libraries such as html2canvas or dom-to-image to simplify the process of taking screenshots of your HTML page and save them as image files.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe