Reputation: 62
I wrote a small JavaScript-based paint program using a HTML5 canvas. What I'm trying to implement now is the ability to save the drawing to a folder on a server. The filename should be something like this: "artist"+"title"+"date" (I'm using prompts to get the artist name and the title). How can I do this? I know I have to do something like this:
var dataURL = canvas.toDataURL();
and then use Ajax to call a PHP script. For example:
$.ajax({
type: "POST",
url: "saveImg.php",
data: {
imgBase64: dataURL
}
}).done(function(o) {
console.log('saved');
});
But how do I get the artist name and the title to the PHP script? As far as I know the file name is defined inside the PHP script, right?
Greetings
Upvotes: 0
Views: 2147
Reputation: 32869
This could be accomplished in the following way ...
ᴊᴀᴠᴀꜱᴄʀɪᴘᴛ
var dataURL = canvas.toDataURL();
$.post('saveImg.php', {
imgBase64: dataURL,
artist: 'ramy',
title: 'paint',
date: new Date().toDateString()
}, function(o) {
console.log('saved');
});
ᴘʜᴘ
<?php
$img = $_POST['imgBase64'];
$artist = $_POST['artist'];
$title = $_POST['title'];
$date = $_POST['date'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$fileData = base64_decode($img);
$fileName = 'images/'.$artist.'_'.$title.'_'.$date.'.png';
file_put_contents($fileName, $fileData);
Upvotes: 1