Convert HTML to Canvas and Canvas to downloadable png / jpeg image | html2canvas. Hello friends in this video i will be showing you how to convert html elements to canvas and how to convert canvas to image which can be downloable in client side. In this tutorial I'm using html2canvas . js library to convert html element to canvas. i hope you will like this video.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Importing the html2canvas library from CDN -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.3.0/html2canvas.min.js"></script>
<title>div 2 jpg using html2canvas js library</title>
<!-- Styling for the result container -->
<style>
.result {
display: none;
}
/* Styling for the canvas element */
canvas {
border: 2px solid blue;
}
</style>
</head>
<body>
<!-- Div element that we want to convert to an image -->
<div class="html">
<h2>Lorem ipsum dolor sit amet.</h2>
<p>
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Facere repudiandae ea libero aspernatur voluptas,
possimus iste distinctio sed alias cum officiis quo quis iure explicabo, nulla assumenda asperiores
temporibus commodi. Laudantium libero corrupti nisi ab earum, sunt laborum, deleniti ducimus totam quod,
deserunt enim consequatur aspernatur soluta nulla eveniet natus!
</p>
<button onclick="convert()">Convert me to jpg image</button>
</div>
<!-- Container to show the result -->
<div class="result">
<!-- Link to download the image -->
<a href=""><button>Download JPG</button></a>
<hr>
</div>
<!-- Script for converting div to image -->
<script>
// Get the div element and the result container
const div = document.querySelector(".html");
const result = document.querySelector(".result");
// Function that converts the div to an image
function convert() {
html2canvas(div).then(function (canvas) {
// Add the canvas element to the result container
result.appendChild(canvas);
// Get the canvas element and convert it to a data URI
let cvs = document.querySelector("canvas");
let dataURI = cvs.toDataURL("image/jpeg");
// Get the link element to download the image and update its properties
let downloadLink = document.querySelector(".result>a");
downloadLink.href = dataURI;
downloadLink.download = "div2canvasimage.jpg";
// Log the data URI to the console
console.log(dataURI);
});
// Show the result container
result.style.display = "block";
}
</script>
</body>
</html>