javascript - save canvas image to server


I'm trying to save the canvas image to the server. I can save the file, but it's always 0 bytes. What's wrong with my code?

function test(){
var canvas  = document.getElementById("cvs");
var dataURL = canvas.toDataURL();

  type: "POST",
  url: "upload.php",
  data: { 
     imgBase64: dataURL
}).done(function(o) {




define('UPLOAD_DIR', 'uploads/');
$img = $_POST['img'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';



First you have to be sure that you have painted to the canvas after you defined thecanvas variable and before you created thedataURL

Second, it seems like you are looking forimg in this php line:

$img = $_POST['img'];

but in your javascript you are defining it asimgBase64 in:

data: { 
   imgBase64: dataURL

lastly you should be addingconsole.log(dataURL) after thedataURL has been created to be sure that there is anything in it.

People are also looking for solutions to the problem: php - looking up results in another table and printing out on webpage


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.