In this post, we will learn how to save an HTML element as an image from a webpage.
To convert or save any HTML element or entire webpage as an image we can use the html2canvas npm package. It lets us convert any div into an image that we can save as an image.
The html2canvas helps users to take screenshots of the whole webpage or a part of it directly on the user’s web browser.
Let’s see how to use it on our website using an example.
Save Element as Image using JavaScript
HTML Code:
<div id="cpimg" style="padding: 15px; background: #86d829;">
<h4>Hello world!</h4>
</div>
<button id="capture" style="margin-top: 30px;">Capture Image</button>
<div class="preview" id="preview">
<h2>Preview Image</h2>
</div>
Here, we have a div with an id (cpimg), we will convert this div into an image using javascript.
Next, we have a button that will run the function to convert the div element into an image.
And the last div with id preview is where we will display the converted image.
Now let’s write the JavaScript code that will do the entire conversion of the element.
Script code:
<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
<script>
const convertBtn = document.getElementById("capture");
const preview = document.getElementById("preview");
convertBtn.addEventListener("click", (e) => {
e.preventDefault();
html2canvas(document.querySelector("#cpimg")).then((canvas) => {
preview.appendChild(canvas);
});
});
</script>
Here, in the script section, we have first added the html2canvas
cdn.
Note: The htmt2canvas lets you install the package using npm command too. However, we have used the cdn for the example.
Next, we have selected the button and the image preview div with the help of getElementById()
method.
We have added a click
event listener to our button so that when a user clicks the Capture Image
button on the web page the html2canvas()
function gets triggered.
This function captures the element in the cpimg
div and converts it into an image and then appends the result to the preview
div on the web page.
To save the image, we just have to right-click the image in the preview section and select “save image as…” to save it on your computer.
Demo code:
Conclusion: So this is how you can convert any div into an image without using canvas on your own. You can also use html2canvas to take screenshots of the entire page with ease.