Javascript Course

The script presented in this page can be used to get canvas image and save it on server, in PNG format.

• To download the script, click this link: Save Canvas Image on Server (9 KB).

The script contains a button that, when it is clicked, the base64 image data of the canvas is send with Ajax to a PHP script that decodes it and save it into a folder on server; and a Div where the Ajax response is displayed.
Before to send the image to server, the script will display a Prompt dialog where you can set a name for the canvas-image. If you let the Prompt dialog empty, the PHP script will set an unique name with uniqid() function.

- Add the html /javascript code into your page, and the "save_cnvimg.php" file in the same folder.
- You can delete the #cnv1 canvas element. Replace 'cnv1' in the JavaScript code with the ID of your canvas.
- In the UPLOAD_DIR constant, in php code, set the path to the upload folder on your server.

HTML JavaScript code

- Click on the code to select it.
<canvas id="cnv1" width="400" height="280"></canvas>
<button id="btn_cnvimg">Save Canvas Image</button>
<div id="ajaxresp">Ajax response</div>
<script>
var cnv = document.getElementById('cnv1');  //Replace 'cnv1' with your canvas ID
var php_file ='save_cnvimg.php';  //address of php file that get and save image on server

/* 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 ='';
  for(var k in data) {
    str_data += k +'='+ data[k].replace(/\?/g, '?').replace(/=/g, '=').replace(/&/g, '&').replace(/[ ]+/g, ' ') +'&'
  }
  str_data = str_data.replace(/&$/, '');  //delete ending &

  //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);
  }
}

//register click on #btn_cnvimg to get and save image
var btn_cnvimg = document.getElementById('btn_cnvimg');
if(btn_cnvimg) btn_cnvimg.addEventListener('click', function(e){
  var imgname = window.prompt('Set a name for the image.\n- If you set a name that already exists,\n the image will be replaced with current canvas-image\n\nLeave empty to let the script set an unique name.', '');

  if(imgname !== null){
    //set data that will be send with ajaxSend() to php (base64 PNG image-data of the canvas, and image-name)
    var img_data = {'cnvimg':cnv.toDataURL('image/png', 1.0), 'imgname':imgname};

    //send image-data to php file
    ajaxSend(img_data, php_file, 'post', function(resp){
      //show server response in #ajaxresp, if not exist, alert response
      if(document.getElementById('ajaxresp')) document.getElementById('ajaxresp').innerHTML = resp;
      else alert(resp);
    });
  }
});
</script>

Code of the save_cnvimg.php file

<?php
define('UPLOAD_DIR', 'uploads/');  //Upload folder

//get properly base64 image data passed via post in 'cnvimg'
$cnvimg = trim(strip_tags($_POST['cnvimg']));
$cnvimg = str_replace('data:image/png;base64,', '', $cnvimg);
$cnvimg = str_replace(' ', '+', $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'; 
$success = file_put_contents($file, $data);

//output response (link to image file, or error message)
print $success ? 'Image: <a href="'. $file .'" target="_blank">'. $file .'</a>' : 'Unable to save the file.';

Demo

- Click on the "Save Canvas Image" button to save the canvas image on server. In this demo, the image name will not be changed.
Ajax response

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag defines the clickable areas inside the image map?
<map> <img> <area>
<img src="image.jpg" usemap="#map1">
<map name="map1">
  <area shape="rect" coords="9, 120, 56, 149" href="#">
  <area shape="rect" coords="100, 200, 156, 249" href="#">
</map>
Which CSS property defines what is done if the content in a box is too big for its defined space?
display overflow position
#id {
  overflow: auto;
}
Click on the event which is triggered when the mouse is positioned over an object.
onclick onmouseover onmouseout
document.getElementById("id").onmouseover = function(){
  document.write("Have Good Life");
}
Indicate the PHP variable that contains data added in URL address after the "?" character.
$_SESSION $_GET $_POST
if(isset($_GET["id"])) {
  echo $_GET["id"];
}
Ajax script to Save Canvas Image on Server

Last accessed pages

  1. Node.js Working with Directories (2049)
  2. SHA1 Encrypt data in JavaScript (35319)
  3. Node.js Move and Copy Directory (19973)
  4. PuzzleImg - Script to Create Image Puzzle Game (9402)
  5. PHP getElementById and getElementsByTagName (49140)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (250)
  2. Read Excel file data in PHP - PhpExcelReader (88)
  3. The Four Agreements (73)
  4. PHP Unzipper - Extract Zip, Rar Archives (73)
  5. The Mastery of Love (65)
Chat
Chat or leave a message for the other users
Full screenInchide