Javascript Course

The JavaScript script presented in this page can be used to take Screenshot of web page (or a specified html element) and Save it to Server with PHP.
It uses html2canvas to get the screenshoot in JavaScript, and Ajax to send base64 screenshoot data to a PHP script that saves the screenshoot in a PNG image file on server.

- Demo save page screenshoot

- Download Script - Save page screenshoot (92 KB)
Or:

1. Get html2canvas.js from: html2canvas and save it in a JS file on your server (for example in "html2canvas.js").

2. Copy the following code and save it in a php file on your server, called save_screenshoot.php:
<?php
define('UPLOAD_DIR', 'screenshoot/'); //folder to save screenshoot

//get properly base64 image data passed via post in 'cnvimg'
$cnvimg = trim(strip_tags($_POST['cnvimg']));
$cnvimg = str_replace(['data:image/png;base64,', ' '], ['', '+'], $cnvimg);

//set image name from 'imgname', or unique name set with uniqid()
$imgname = (isset($_POST['imgname']) && !empty(trim($_POST['imgname']))) ? trim(strip_tags($_POST['imgname'])) : uniqid();

//get image data from base64 and save it on server
$data = base64_decode($cnvimg);
$file = UPLOAD_DIR . $imgname .'.png'; 
$save = file_put_contents($file, $data);

//set and output response
$resp = $save ?['re'=>$file] :['er'=>'Unable to save: '. $file];
echo json_encode($resp);

3. Copy the following code and save it in a JS file on your server, called "save_screenshoot.js":
//from: https://coursesweb.net/
function saveScreenshoot(ob){
 var php_file ='save_screenshoot.php'; //address of php file that get and save image on server
 var html_elm =(ob && ob.elm) ? ob.elm :'body'; //css selector of html element to get screenshoot
 var imgname =(ob && ob.img) ? ob.img : location.pathname.match(/[^\/]+$/i)[0].replace(/\.(.*?)$/i, ''); //name of the image to save (page name without extension)

 /* Ajax Function
 Send "data" to "php", using the method added to "via", and pass response to "callback" function
 data - object with data to send, name:value; ex.: {"name1":"val1", "name2":"2"}
 php - address of the php file where data is send
 via - request method, a string: 'post', or 'get'
 callback - function called to proccess the server response
 */
 function ajaxSend(data, php, via, callback) {
 var ob_ajax = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); //XMLHttpRequest object

 //put data from 'data' into a string to be send to 'php'
 var str_data ='isajax=1';
 for(var k in data){
 k = k.toString();
 if(data[k] || data[k] ==''){
 str_data +='&'+ k +'='+ data[k].toString().replace(/\?/g, '?').replace(/=/g, '=').replace(/&/g, '&').replace(/[ ]+/g, ' ').replace(/[\+]/g, '+');
 }
 }

 //send data to php
 ob_ajax.open(via, php, true);
 if(via =='post') ob_ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
 ob_ajax.send(str_data);

 //check the state request, if completed, pass the response to callback function
 ob_ajax.onreadystatechange = function(){
 if (ob_ajax.readyState == 4) callback(ob_ajax.responseText);
 }
 }

 var getScreenshoot = function(){
 //Uses HTML2Canvas to capture screenshoot of <body> content
 html2canvas(document.querySelector(html_elm)).then(canvas => {
 //get base64 string data of the screenshoot
 var base64image = canvas.toDataURL('image/png');

 //set data that will be send with ajaxSend() to php (base64 image-data of the canvas, and image-name)
 var img_data = {cnvimg:base64image, imgname:imgname};

 //send image-data to php file, then alert response
 ajaxSend(img_data, php_file, 'post', function(resp){
 var resp = JSON.parse(resp) ||{};
 if(resp.re && scrn_img) scrn_img.innerHTML ='<a href="'+resp.re+'" target="_blank">See Screenshoot</a>';
 else if(resp.er) alert(resp.er);
 });
 });
 }

 //add button Save-Screenshoot in the page to call getScreenshoot() on click
 var js_save_scrht = document.getElementById('js_save_scrht');
 if(js_save_scrht){
 js_save_scrht.insertAdjacentHTML('beforebegin', '<div id="scrn_btn_img" style="text-align:center;margin:8px auto;"><button id="btn_save_scrht">Save Screenshoot</button><h4 id="scrn_img"></h4></div>');
 var scrn_btn_img = document.getElementById('scrn_btn_img');
 var btn_save_scrht = document.getElementById('btn_save_scrht');
 var scrn_img = document.getElementById('scrn_img');
 if(btn_save_scrht) btn_save_scrht.addEventListener('click', (e)=>{
 scrn_btn_img.style.display ='none';
 getScreenshoot();
 window.setTimeout(function(){ scrn_btn_img.style.display ='block';}, 1000);
 });
 }
}

4. Add the following code to the end of the html page content (before the ending tag </body>):
<script src="html2canvas.js"></script>
<script src="save_screenshoot.js" id="js_save_scrht"></script>
<script>
//css selector that represents the html element to which to take screenshoot
var scrn_elm ='body'; //for example: #id_elm

//name of the PNG image with the screenshoot to save on server
//here, page name without extension
var scrn_img = location.pathname.match(/[^\/]+$/i)[0].replace(/\.(.*?)$/i, '');

//object that get the screenshoot
var save_scrht = new saveScreenshoot({elm:scrn_elm, img:scrn_img});
</script>

- In the scrn_elm variable it is defined the css selector that represents the html element to which to take screenshoot. Default "body", takes a screenshoot of all the page.
- In the scrn_img variable it is defined the name of the PNG image with the screenshoot to save on server. Default, page name from URL (without extension).

The script will display a "Save Screenshoot" button in the place where you add the code above.
When that button is clicked, it will be hidden to not be included in image, then the screenshoot is sent with ajax to the php script which will save it in a png image file on server.
After the screenshoot is saved, the ajax script will add a "See Screenshoot" link (after button) which will open a window with the PNG image.

Demo: html2canvas - Save page screenshoot

Wait a few seconds to load data. Then will be displayed a Select box to choose what screenshoot to take, then click on the button, it will open a pop-up with selected screenshoot.

Getting Screenshoot..

-
Allow your browser to open the pop-up window.
Waith a few seconds till the image is created.

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag is used to add lists into <ul> and <ol> elements?
<dt> <dd> <li>
<ul>
 <li>http://coursesweb.net/html/</li>
 <li>http://coursesweb.net/css/</li>
</ul>
Which value of the "display" property creates a block box for the content and ads a bullet marker?
block list-item inline-block
.some_class {
  display: list-item;
}
Which instruction converts a JavaScript object into a JSON string.
JSON.parse() JSON.stringify eval()
var obj = {
 "courses": ["php", "javascript", "ajax"]
};
var jsonstr = JSON.stringify(obj);
alert(jsonstr);    // {"courses":["php","javascript","ajax"]}
Indicate the PHP class used to work with HTML and XML content in PHP.
stdClass PDO DOMDocument
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>';
$dochtml = new DOMDocument();
$dochtml->loadHTML($strhtml);
$elm = $dochtml->getElementById("dv1");
echo $elm->nodeValue;    // CoursesWeb.net
html2canvas - Save page screenshoot on server

Last accessed pages

  1. sPBM - Simple PHP Backup Manager (3402)
  2. Vue JS - Transition and Animation (490)
  3. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (141749)
  4. Node.js Move and Copy file (28420)
  5. MouseEvent - Events for Mouse (2909)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (473)
  2. CSS cursor property - Custom Cursors (79)
  3. The Mastery of Love (70)
  4. PHP-MySQL free course, online tutorials PHP MySQL code (62)
  5. CSS3 2D transforms (46)