Take a Screenshot Using Html2Canvas JS


In previous post I have explained about Feedback with screenshot using feedback JS, which is using Html2Canvas JS to take a screenshot, now In this tutorial I will show how you can take a screenshot using Html2Canvas JS. This script allows you take a screenshot of a part of the web page also.

You can download Html2Canvas jQuery plugin from https://github.com/niklasvh/html2canvas/releases. Following is an example to take a screenshot of full web page.

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="html2canvas.js"></script>
<script type="text/javascript">

	html2canvas(document.body, {
		onrendered: function(canvas)
		{
		    var img = canvas.toDataURL()
			$.post("save.php", {data: img}, function (file) {
				window.location.href =  "download.php?path="+ file
			});
		}
	});

</script>

If you want to take a screenshot of a specific part of the web page, you need to provide particular area div id as in below example:

html2canvas([document.getElementById('div-id')], {
	onrendered: function(canvas)
	{
		var img = canvas.toDataURL()
		$.post("save.php", {data: img}, function (file) {
			window.location.href =  "download.php?path="+ file
		});
	}
});

Now create a file save.php to save the screenshot as an image and write following code:

$data = $_POST['data'];
$file = md5(uniqid()) . '.png';

// remove "data:image/png;base64,"
$uri =  substr($data,strpos($data,",")+1);

// save to file
file_put_contents('./'.$file, base64_decode($uri));

// return the filename
echo $file; exit;

Now create a file download.php to download the image and paste following code:

$file = trim($_GET['path']);

// force user to download the image
if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: image/png');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    unlink($file);
    exit;
}
else {
    echo "$file not found";
}

This tutorial will help you to take a screenshot of the page and download as an image to use further. Hope this post will help you.

Live Demo