Home / Snippets / How to save div as image with Html2Canvas with AJAX request
How to save div as image with Html2Canvas with AJAX request cover

How to save div as image with Html2Canvas with AJAX request

2.3K

3 years ago

0 comments

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.

HTML Code


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>
</div>

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

html2canvas(specialDiv)
    .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
        ajax.open('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
                console.log(this.responseText);
            }
        };
    });

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

notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this