Save div as image – Html2Canvas

5
(2)

First you need to download the library called Html2Canvas and paste in your project folder. You can download it from here. After that, paste the JS file in your project and include it via script tag.

<script src="html2canvas.js"></script>

Then give a unique ID to the div tag whose screenshot you wants to take. After that, create a function in Javascript which will be called when you want to take the screenshot. We will be calling that function on some button press, but you can use it as per your needs.

<script>
	// A function to convert the required div to image
	function doCapture() {
		//
	}
</script>

<button onclick="doCapture();">Capture</button>

In order to make this library works, your scroll position should be on header of your site. Even if you want to take the screenshot of footer or any other section in the middle, your header must be visible before converting the div to image. So we will move the scroll to top by simply calling the window.scrollTo(x, y) function and pass the x, y coordinates as 0 both.

function doCapture() {
	// Move the scroll on top of page
	window.scrollTo(0, 0);
}

Now we need to call the html2canvas function, it’s first parameter will be the tag which needs to be converted as image. As we already would have given it some unique ID attribute, so we can get it easily by calling document.getElementById(id) function. Lastly the library provides a function called then() which sends a callback when the div has been converted to image successfully. Basically it sends a canvas object and we can get the image data from that canvas. We can call the toDataURL(imageType, quality) function to get the image type. Possible image types are “image/jpeg” or “image/png” and the value of quality parameter ranges from 0 to 1. By setting the value to 0.9 we can get the minimum compression and maximum quality on image.

function doCapture() {
	window.scrollTo(0, 0);

	// Convert the div to image (canvas)
	html2canvas(document.getElementById("capture")).then(function (canvas) {

		// Get the image data as JPEG and 0.9 quality (0.0 - 1.0)
		console.log(canvas.toDataURL("image/jpeg", 0.9));
	});
}

In order to save this image in our server, you need to call an AJAX request and pass this image data as parameter.

function doCapture() {
	window.scrollTo(0, 0);

	html2canvas(document.getElementById("capture")).then(function (canvas) {

		// Create an AJAX object
		var ajax = new XMLHttpRequest();

		// Setting method, server file name, and asynchronous
		ajax.open("POST", "save-capture.php", true);

		// Setting headers for POST method
		ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

		// Sending image data to server
		ajax.send("image=" + canvas.toDataURL("image/jpeg", 0.9));

		// Receiving response from server
		// This function will be called multiple times
		ajax.onreadystatechange = function () {

			// Check when the requested is completed
			if (this.readyState == 4 && this.status == 200) {

				// Displaying response from server
				console.log(this.responseText);
			}
		};
	});
}

Now create a server file named save-capture.php and paste the following code to save the incoming data as image.

<?php

// Get the incoming image data
$image = $_POST["image"];

// Remove image/jpeg from left side of image data
// and get the remaining part
$image = explode(";", $image)[1];

// Remove base64 from left side of image data
// and get the remaining part
$image = explode(",", $image)[1];

// Replace all spaces with plus sign (helpful for larger images)
$image = str_replace(" ", "+", $image);

// Convert back from base64
$image = base64_decode($image);

// Save the image as filename.jpeg
file_put_contents("filename.jpeg", $image);

// Sending response back to client
echo "Done";

Kindly login or create a new account to download the files.

How useful was this post

Click on a star to rate it!

Average rating 5 / 5. Vote count: 2

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post





5 Replies to “Save div as image – Html2Canvas”

Comments are closed.

Please disable your adblocker or whitelist this site!