Question

I have this canvas. I have written some javascript that allows the user to draw on the canvas in different colors and pen sizes.

<style>
#myCanvas{
position:absolute;
top:0px;
left:0px;
border:1px solid black;
z-index:0;
}
</style>

<canvas id="myCanvas" width="900" height="600"></canvas>

How would I have the user click on a button or an input with type="button" and have the image save to the server?

Was it helpful?

Solution

You can save your canvas artwork as an encoded image with canvas.toDataURL

Then you can use AJAX to submit that encoded image data to your server.

Here's some code using jQuery+AJAX to POST the image data to a file on your server.

Client Side in your button-click event:

// create a dataUrl from the canvas

var dataURL= canvas.toDataURL();

// post the dataUrl to php

$.ajax({
  type: "POST",
  url: "upload.php",
  data: {image: dataURL}
}).done(function( respond ) {
  // you will get back the temp file name
  // or "Unable to save this image."
  console.log(respond);
});

You didn't mention what server you're using, but PHP is a common server.

Server File: upload.php

<?php

// make sure the image-data exists and is not empty
// xampp is particularly sensitive to empty image-data 
if ( isset($_POST["image"]) && !empty($_POST["image"]) ) {    

    // get the dataURL
    $dataURL = $_POST["image"];  

    // the dataURL has a prefix (mimetype+datatype) 
    // that we don't want, so strip that prefix off
    $parts = explode(',', $dataURL);  
    $data = $parts[1];  

    // Decode base64 data, resulting in an image
    $data = base64_decode($data);  

    // create a temporary unique file name
    $file = UPLOAD_DIR . uniqid() . '.png';

    // write the file to the upload directory
    $success = file_put_contents($file, $data);

    // return the temp file name (success)
    // or return an error message just to frustrate the user (kidding!)
    print $success ? $file : 'Unable to save this image.';

}

Some usual gotchas:

  • Make sure you have properly set up your upload directory.

  • Make sure you have permissions set properly on the upload directory.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top