Asked  2 Years ago    Answers:  5   Viewed   82 times

I'm working on a generative art project where I would like to allow users to save the resulting images from an algorithm. The general idea is:

  • Create an image on an HTML5 Canvas using a generative algorithm
  • When the image is completed, allow users to save the canvas as an image file to the server
  • Allow the user to either download the image or add it to a gallery of pieces of produced using the algorithm.

However, I’m stuck on the second step. After some help from Google, I found this blog post, which seemed to be exactly what I wanted:

Which led to the JavaScript code:

function saveImage() {
  var canvasData = canvas.toDataURL("image/png");
  var ajax = new XMLHttpRequest();"POST", "testSave.php", false);
  ajax.onreadystatechange = function() {
  ajax.setRequestHeader("Content-Type", "application/upload");
  ajax.send("imgData=" + canvasData);

and corresponding PHP (testSave.php):

if (isset($GLOBALS["HTTP_RAW_POST_DATA"])) {
  $imageData = $GLOBALS['HTTP_RAW_POST_DATA'];
  $filteredData = substr($imageData, strpos($imageData, ",") + 1);
  $unencodedData = base64_decode($filteredData);
  $fp = fopen('/path/to/file.png', 'wb');

  fwrite($fp, $unencodedData);

But this doesn’t seem to do anything at all.

More Googling turns up this blog post which is based off of the previous tutorial. Not very different, but perhaps worth a try:

$data = $_POST['imgData'];
$file = "/path/to/file.png";
$uri = substr($data,strpos($data, ",") + 1);

file_put_contents($file, base64_decode($uri));
echo $file;

This one creates a file (yay) but it’s corrupted and doesn’t seem to contain anything. It also appears to be empty (file size of 0).

Is there anything really obvious that I’m doing wrong? The path where I’m storing my file is writable, so that isn’t an issue, but nothing seems to be happening and I’m not really sure how to debug this.


Following Salvidor Dali’s link I changed the AJAX request to be:

function saveImage() {
  var canvasData = canvas.toDataURL("image/png");
  var xmlHttpReq = false;

  if (window.XMLHttpRequest) {
    ajax = new XMLHttpRequest();
  else if (window.ActiveXObject) {
    ajax = new ActiveXObject("Microsoft.XMLHTTP");
  }"POST", "testSave.php", false);
  ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  ajax.onreadystatechange = function() {
  ajax.send("imgData=" + canvasData);

And now the image file is created and isn’t empty! It seems as if the content type matters and that changing it to x-www-form-urlencoded allowed the image data to be sent.

The console returns the (rather large) string of base64 code and the datafile is ~140 kB. However, I still can’t open it and it seems to not be formatted as an image.



Here is an example of how to achieve what you need:

  1. Draw something (taken from canvas tutorial)

<canvas id="myCanvas" width="578" height="200"></canvas>
  var canvas = document.getElementById('myCanvas');
  var context = canvas.getContext('2d');

  // begin custom shape
  context.moveTo(170, 80);
  context.bezierCurveTo(130, 100, 130, 150, 230, 150);
  context.bezierCurveTo(250, 180, 320, 180, 340, 150);
  context.bezierCurveTo(420, 150, 420, 120, 390, 100);
  context.bezierCurveTo(430, 40, 370, 30, 340, 50);
  context.bezierCurveTo(320, 5, 250, 20, 250, 50);
  context.bezierCurveTo(200, 5, 150, 20, 170, 80);

  // complete custom shape
  context.lineWidth = 5;
  context.fillStyle = '#8ED6FF';
  context.strokeStyle = 'blue';
  1. Convert canvas image to URL format (base64)

    var dataURL = canvas.toDataURL();

  2. Send it to your server via Ajax

      type: "POST",
      url: "script.php",
      data: { 
         imgBase64: dataURL
    }).done(function(o) {
      // If you want the file to be visible in the browser 
      // - please modify the callback in javascript. All you
      // need is to return the url to the file, you just saved 
      // and than put the image in your browser.
  1. Save base64 on your server as an image (here is how to do this in PHP, the same ideas is in every language. Server side in PHP can be found here):
Sunday, November 13, 2022

You should check link I refered in comment its your complete answer.

here is a Simple example with your code.

    // Set alerts as array 
$error     = "";

    // I should just trrim and let you check if email is empty .lol 
if (empty($_POST["email_val"])) {
    $error .= "<p class='error'>Fill email value.</p>";

    //Check if this is a real email 
} elseif(!filter_var($_POST["email_val"],FILTER_VALIDATE_EMAIL)){
    $error .= "<p class='error'>Wrong email type.</p>";
    $email = mysqli_real_escape_string($conn, $_POST["email_val"]);

    //You should use prepare statement $email, Shame on you .lol    
    $query = "SELECT * FROM customer WHERE email = '{$email}'");
    $result = mysqli_query($conn, $query);
    echo mysqli_num_rows($result);
    $error .= "ok";
$data = array(
 'error'  => $error

This Jquery :

    var formValues = $(this).serialize();
                if(data.error === 'ok'){
                } else {

And Html :

<form id="myform">
  <input class="input--style-4" id="email" type="email" name="email_val">
  <span id="result"></span>
  <button type="button" class="btn btn-primary">Send</button>
Monday, August 29, 2022

In order to update charts that way, you need to create chart only once (outside the ajax request) and keep adding new dataPoints via ajax request each second as shown below.

        <script type="text/javascript" src="canvasjs.min.js"></script>
        <script src=""></script>
            $(document).ready(function () {
                var chart = new CanvasJS.Chart("chartContainer", {

                    zoomEnabled: true,
                    panEnabled: true,
                    animateEnabled: true,
                    data: [ {
                        type: "splineArea",
                        xValueType: "label",
                        y: "y",
                        dataPoints: [] 
                    } ] 


                function updateChart(){
                    $.getJSON("data.php", function (data_points) {
                        for(var i = 0; i < data_points.length; i++){


                var updateInterval = 1000;

                }, updateInterval);


        <div id="chartContainer" style="height: 300px; width: 500px;"></div>
Friday, December 2, 2022

If you just want to pass a reference to your Activity use: MakeCall.this (or maybe just this.)

Sunday, October 2, 2022

You could dynamically add your scripts, in that way they are loaded asynchronously by default.

To ensure an ordered execution you could mark them explicitly as not async.

Here is a minimum example:

            ].forEach(function(src) {
                var script = document.createElement('script');
                script.src = src;
                script.async = false;


The File 1.js contains jquery code:

$("body").append("<div>It works</div>");

In this example the files are loaded asynchrounously but keep the specified order. For further reading you can have a look at:

Saturday, August 20, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :

Browse Other Code Languages