Posts Learn Components Snippets Categories Tags Tools new About

How to save div as image with Html2Canvas with AJAX request

Learn how to capture a screenshot of a div or any other tags with Html2Canvas

Created on Aug 24, 2021


In this short snippet, you will learn how to capture a screenshot of a div tag, iframe tag, or any of the elements inside of a webpage using html2canvas and storing the image in your backend application using a plain AJAX request.


Define the HTML that you want to screenshot as you see fit and assign an "id" to be called by html2canvas.
<div id="special-div">
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p>

AJAX Request

To create an AJAX request to save the image you can write the code as follows
let specialDiv = document.getElementById('special-div'); // getting special div

    .then(canvas => {
        // create a new AJAX object
        var ajax = new XMLHttpRequest();

        // set the method to use, the backend file and set it requst as asynchrounous'POST', 'screenshot-page.php', true);

        // set the request headers 
        ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

        // set the image type to "img/jpeg" and qualty to 1 (100%)
        ajax.send("image=" + canvas.toDataURL("image/jpeg", 1));

        ajax.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                // display the response sent from server

Backend Logic To Save Image

The backend logic that is responsible to save the image on the backend is as follows.
<?php // screenshot-page.php
// get the incoming image data sent by the AJAX request
$screenshotImage = $_POST["image"];
// remove image/jpeg from left side of image data and get the remaining part
$screenshotImage = explode(";", $screenshotImage)[1];
// remove base64 from left side of image data and get the remaining part
$screenshotImage = explode(",", $screenshotImage)[1];
// replace all spaces with plus sign (helpful for larger images)
$screenshotImage = str_replace(" ", "+", $screenshotImage);
// convert back from base64 format
$screenshotImage = base64_decode($screenshotImage);
// save the image as filename.jpeg
file_put_contents("screenshot-image.jpeg", $screenshotImage);
// provide a response to the front-end
echo "Done";

Other Reads

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️