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 is used to add definition lists into a <dl> element?
<dt> <dd> <li>
<dl>
 <dt>HTML</dt>
  <dd> - Hyper Text Markup Language</dd>
  <dd> - Language for web pages</dd>
</dl>
Which CSS property can hide an element on page, letting an empty space in its place?
display position visibility
#id {
  visibility: hidden;
}
Click on the event which is triggered when the mouse clicks on an object.
onclick onmouseover onfocus
document.getElementById("id").onclick = function(){
  alert("http://CoursesWeb.net/");
}
Indicate the PHP variable that contains the contents of both $_GET, $_POST, and $_COOKIE arrays.
$_SESSION $_GET $_REQUEST
if(isset($_REQUEST["id"])) {
  echo $_REQUEST["id"];
}
Ajax script to Save Canvas Image on Server

Last accessed pages

  1. PHP MySQL - SELECT, ORDER BY (8982)
  2. Frog Dares (157)
  3. Action Games (4889)
  4. Voting Poll System script PHP-AJAX (5308)
  5. Amazing Escape (241)

Popular pages this month

  1. Bubbles3 (3136)
  2. Butterfly Kyodai (2748)
  3. Zuma Deluxe (2025)
  4. Qwop (1252)
  5. Backgammon (1197)