Html2Canvas is a JavaScript library that allows you to take a screenshot of the entire web page or a specific section with just a few lines of code.
It returns an HTML5 canvas element when it is initialized on the element that you can use to create a new image file or display a screenshot preview on the screen.
In this tutorial, I show how you can use Html2Canvas library to take a screenshot and save it to the server using PHP.
Contents
- Download and Include
- Initialize
- Example 1 – Full page screenshot
- Example 2 – Screenshot of specific area
- Example 3 – Save screenshot to the server
- Conclusion
1. Download and Include
- Download the library from GitHub.
- Include
html2canvas.jsscript at the<head>.
<script type="text/javascript" src="html2canvas-master/dist/html2canvas.js"></script>
2. Initialize
Call html2canvas() method which takes selector as a parameter and with then handle canvas response.
html2canvas(document.body).then(function(canvas) {
document.body.appendChild(canvas);
});
canvas.toDataURL()
This method returns the base64 value which you can use to create an image source or an image file.
html2canvas(document.getElementById('container')).then(function(canvas) {
document.getElementById("image").src= canvas.toDataURL();
});
3. Example 1 – Full page screenshot
Take a screenshot of the full page and show a preview.
Completed Code
<!doctype html>
<html>
<head>
<script type="text/javascript" src="html2canvas-master/dist/html2canvas.js"></script>
</head>
<body>
<h1>Take screenshot of webpage with html2canvas</h1>
<div class="container" id='container' >
<img src='images/image1.jpg' width='100' height='100'>
<img src='images/image2.jpg' width='100' height='100'>
<img src='images/image3.jpg' width='100' height='100'>
</div>
<input type='button' id='but_screenshot' value='Take screenshot' onclick='screenshot();'><br/>
<!-- Script -->
<script type='text/javascript'>
function screenshot(){
html2canvas(document.body).then(function(canvas) {
document.body.appendChild(canvas);
});
}
</script>
</body>
</html>
4. Example 2 – Screenshot of specific area
In this example, I am taking a screenshot of <div id='container'> content.
Completed Code
<!doctype html>
<html>
<head>
<script type="text/javascript" src="html2canvas-master/dist/html2canvas.js"></script>
</head>
<body>
<h1>Take screenshot of webpage with html2canvas</h1>
<div class="container" id='container' >
<img src='images/image1.jpg' width='100' height='100'>
<img src='images/image2.jpg' width='100' height='100'>
<img src='images/image3.jpg' width='100' height='100'>
</div>
<input type='button' id='but_screenshot' value='Take screenshot' onclick='screenshot();'><br/>
<!-- Script -->
<script type='text/javascript'>
function screenshot(){
html2canvas(document.getElementById('container')).then(function(canvas) {
document.body.appendChild(canvas);
});
}
</script>
</body>
</html>
5. Example 3 – Save screenshot to the server
HTML –
Create a similar HTML layout as the above example and include the jQuery library.
Script –
Create screenshot() function where initialize html2canvas on the body. By default, html2canvas set the image background color to black if save the screenshot.
With the use of background: '#fff' set background white. Read the screenshot image base64 URL using canvas.toDataURL().
To save image to the server send AJAX POST request to ajaxfile.php where pass base64URL variable as data.
Completed Code
<!doctype html>
<html>
<head>
<script type="text/javascript" src="html2canvas-master/dist/html2canvas.js"></script>
</head>
<body>
<h1>Take screenshot of webpage with html2canvas</h1>
<div class="container" id='container' >
<img src='images/image1.jpg' width='100' height='100'>
<img src='images/image2.jpg' width='100' height='100'>
<img src='images/image3.jpg' width='100' height='100'>
</div><br/>
<input type='button' id='but_screenshot' value='Take screenshot' onclick='screenshot();'><br/>
<!-- Script -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type='text/javascript'>
function screenshot(){
html2canvas(document.body,{background: '#fff'}).then(function(canvas) {
document.body.appendChild(canvas);
// Get base64URL
var base64URL = canvas.toDataURL('image/jpeg').replace('image/jpeg', 'image/octet-stream');
// AJAX request
$.ajax({
url: 'ajaxfile.php',
type: 'post',
data: {image: base64URL},
success: function(data){
console.log('Upload successfully');
}
});
});
}
</script>
</body>
</html>
AJAX file –
Create ajaxfile.php file and upload folder to store the screenshot taken using Html2canvas.
Read $_POST['image'] value and specify upload path in $location. Explode $image by ";base64," and decode base64 value using base64_decode().
Create a unique filename and pass the filename and base64 value to file_put_contets() to store file on the server.
Completed Code
<?php
$image = $_POST['image'];
$location = "upload/";
$image_parts = explode(";base64,", $image);
$image_base64 = base64_decode($image_parts[1]);
$filename = "screenshot_".uniqid().'.png';
$file = $location . $filename;
file_put_contents($file, $image_base64);
6. Conclusion
Html2Canvas is a highly versatile and efficient JavaScript library that allows you to take high-quality screenshots of any webpage with ease on the client browser without server-side interaction.
It might not able to generate the proper view if there is complex CSS applied to the elements.
Browser compatibility –
- Firefox 3.5+
- Google Chrome
- Opera 12+
- IE9+
- Safari 6+

This example is really good.
One quick requirement, Instead of appending to body. Is it possible to download from browser as image.
hi!, how can I take the screenshot of a div?
thanks in advance.
How can we preview it on the same page?
How about saving the screenshot image from the second example on the server?
can you please made an example on how to display the screenshot in a modal?
and how can we display multiple screenshots on a carousal ?
#bootstrap
i used this in my materialize css form, the screen shot in form is not good, maybe because of materialize css, and the rest is good
function saveCanvas(id){
html2canvas(document.getElementById(id)).then(canvas => {
var imageData = canvas.toDataURL(‘image/jpeg’);
var url = ‘my-api-url/images’;
/* save image to server */
$.ajax({
url: url,
type: ‘POST’,
dataType: ‘text’,
data: { myparams: imageData},
success: function(response){
console.log(response)
}
})
})
}
The codes are working in the browser, but the server is not receiving any requests with cron. codes do not work.
This example is really good.
One quick requirement, Instead of appending to body. Is it possible to show in popup?
First of all, thank you Yogesh for the article. I am building an intranet for my organization and had faced a challenge on how to export a div element that displays the employee payslip details with the css styles intact. I tried server side PDF generation techniques but the styling was ugly, damn ugly. I then stumbled upon your blog and it helped me immensely. I ended up converting the div content to a png image and then downloaded it as pdf file
Hi Yogesh,
I am done with the save screenshot step which is downloading an image to download folder. But how can I save the SS to a specific path of in my local directory.
Hello,
This is great stuff and it worked but unfortunately it’s not getting the iframe part when the page got an iframe in it. What’s the workaround for this? Thanks.
Hello, thanks for the topic.
Is it possible to take screenshot of iframe?
Canvas don’t wan’t to take it
Can you help me!. How to change the image size in javascript, please!!
Using example 3, it would be possible to show the image URL (localhost / upload / name_image.png), you just need to show the URL on the image screen that the user just created! Any help would be greatly appreciated! Thank you!
hi, can you give me complete ajaxfile.php example, please? i’m not able to make upload function working alone… thanks 😉
thank u. thank u.thank u.
is it possible to screenshot image display in popup modal ?
Thanks very much for this. Works really well for me.
Saving the file to the server but I had to modify the php file so it saved as jpg, not png as irfanview said it was not a png file but jpg.
I have a couple of things I need to do.
1. I do not wish to see preview. How do I hide this?
2. How do I get file name to be the value in drop down list?
Thanks again. Love it.
I have now resolved this. I had to update the screenshot function to include the following line (where datepicker is the ID from the text input box):
var val1 = $(‘#datepicker’).val();
Then update the ajax data code to the following:
data: {image: base64URL, datepicker: val1},
Finally I had to update the filename code in the php to:
$filename = $_POST[‘datepicker’].’.jpg’;
HIi,
I commented in this forum. But somehow could not see in the above list.
Is it possible to take screenshot of dynamically generated Chart or content using html2canvas because i am not getting desired result.
I am using reactjs and recharts for generating charts from content received via axios from server.
-Arun
any luck on downloading charts?
Hello,
I’am trying to integrate this with angular. Can you provide your insights on that and also how can I make so that the captured image takes up entire screen and then I can perform operations on it like putting markers on it. It will be great help!!
Thanks in advance.
is there any option to take screenshot of alert box?
Can we take chart/graph screenshot?
Hi yogesh,
thank-you for your wonderful article. I want a screen-shot of an html-element having a good amount of css implemented. like css from this site – https://marvelapp.github.io/devices.css/. I am not able to take screenshot from an node with this level of css used.
Can you suggest anything.
Could someone please show a working example of return of $filename I can not seem to get it to work … it displays image but i need a URL of image that has been uploaded.
Hi
Thanks for the cool stuff. I did everything according to example 3 and everything works, but the saved image on the server always has a black background. Preview of the saved DIV is fine, even as it saves the DIV preview to disk via the right mouse button (save image as), everything is also ok. Some hint what may be wrong
Good day!
I went through your blog right now and I am amazed really! You have elaborated your article greatly with precise code and content.
I have implemented this tutorial and it really works. Thanks Yogesh!
Hi, thanks for the code. I like the ajax way of doing this much better! I had an older html2canvas script that was saving a single image.
Now, I’m saving an image and using the date and current time as the image name. I want to email this image every time it gets saved. My old script no longer works. Wondering if you’ve done this before?
Basically — save image then send last saved image to “x” email.
Thanks!
Hi, thanks for the code. Just want to check is any way to open the saved image in a new window/tab? Thanks again!
Sorry, the question is for example 3. And is it posable to open a new HTML page with the saved image? Thank you!
Hello and thank you for the article. I wanted to ask you if instead of showing the image or saving it to the server can Isend it by e-mail among other fields that the user enters?
Thank you so much!
Using HTML2Canvas i cannot generate base64 url for the modal. Can anyone suggest me the idea of how can i do it?
It is working all defined browser but my case it is not woring in IE any version of browsers can you give me suggestion for the same
This example is really good.
Q1: I have targeted a container and downloaded the image. The image looks blurry. Unable to read the content. Is there any way to download it in high resolution.
Q2: In landscape mode, the visible part of the container is downloaded instead of full. Is there any solution to this.
Used code:
function capture(){
html2canvas(document.getElementById(‘profileBox’)).then(function(canvas) {
document.body.appendChild(canvas);
var a = document.createElement(‘a’);
a.href = canvas.toDataURL(“image/jpeg”).replace(“image/jpeg”, “image/octet-stream”);
a.download = ‘SnackSelfie.jpg’;
a.click();
});
}
I wanna take a snapshot of div with the full height now it’s only taking the SS as much size is visible in the screen. any solution?
here’s my code..
html2canvas(input)
.then((canvas) => {
const imgData = canvas.toDataURL(‘image/png’).replace(‘image/jpeg’, ‘image/octet-stream’);
const pdf = new jsPDF();
pdf.addImage(imgData, ‘PNG’, 0, 0);
pdf.save(‘download.pdf’);
});
here’s my code..
html2canvas(input)
.then((canvas) => {
const imgData = canvas.toDataURL(‘image/png’).replace(‘image/jpeg’, ‘image/octet-stream’);
const pdf = new jsPDF();
pdf.addImage(imgData, ‘PNG’, 0, 0);
pdf.save(‘download.pdf’);
});
Hello! thanks for answering:
I have a web page (my site.html) and I want to generate a web page (my site screenshot.html) where I take a screen from the first web page.
should i use getsceen and an iframeload?
thanks!
Hi,
I Got following error.
Failed to load resource: the server responded with a status of 404 (Not Found)
var img = canvas.toDataURL(“image/jpeg”);
This some times returns incomplete data, captured image returned is incomplete.
Is there a way that we can check if the image is complete?
NEED: I want to send that variable img to another function in same java script file which further sends that image over email.
PROBLEM: it returns incomplete data many of the times, that the screenshot is incomplete, or we can say that empty screenshot or blank screenshot
Hi Yogesh,
Thanks for the article.
I want to take snapshot of a page which contains data and a scrollable table. The snapshot should have all the data of page including data from the scrollable table.
function capture(){
window.scrollTo(0, 0);
html2canvas(document.getElementById(‘container’),{ height: document.getElementById(‘container’).scrollHeight}).then(function(canvas) {
// Get base64URL
var base64URL = canvas.toDataURL(‘image/jpeg’).replace(‘image/jpeg’, ‘image/octet-stream’);
// AJAX request
$.ajax({
url: ‘test.php’,
type: ‘post’,
data: {image: base64URL},
success: function(data){
console.log(‘message);
}
});
});
}
You can calculate the scroll height and add use it with heigh property. May this will help you
Hey, Yogesh I downloaded the same example that you are describing but it does not take a screenshot of the image can you please help me in this?
Thanks in Advance
I am getting an blank canvas instead of image any soln?
Hi ~ thanks for giving such wonderful tutorial, it’s really understandable! I just wonder can I apply this technique to another site which not owned by myself. Take screenshot from anysite I want…is it possible….? thanks for teaching …:)
Hi Yogesh,
Thanks for the example, currently I am facing a problem in html2canvas I am using html2canvas screenshot for dynamic data. It works fine for first iteration andfrom second iteration I am getting blank screen
Can you help me please
How do we use in chrome extension. It gives error that html2canvas not defined.
Hi Yogesh,
you are doing an amazing work making the code and documentation part easy for otherr to understand. How can i download the same screenshot in my local on click.
Was searching for a week. This one is the simplest solution I could find. how can we do this instead of specifying div, giving certain screen co-ordinates?
But How can i save that screenshot in my local machine automatically?
google maps not loading in screenshot blank page coming for map
html2canvas(document.body).then(function(canvas) {
document.body.appendChild(canvas);
});