问题
I know there is probably an answer already to this question but I haven't been able to find it yet and there is a deadline on my project.
So I have made an html5 canvas and I would like to be able to do two things with one(or more) buttons. I would like the user to be able to save what he has just done by clicking on the save button and ideally I would like the image to be downloaded (as opposed to having to right click and "Save image as". This is what I have been able to do so far). I would also like the image to be saved (maybe to a database? or a server? I don't know how it works) so that a part of the drawing (or all of it, depending on the difficulty of the code) that has been done before is used the next time someone else logs on (not necessarily the same person with the same IP). Is this possible?
I am very new to code and self teaching myself so any extra comments on the code to help me understand would be extra-appreciated.
回答1:
Regarding the first task, you can export the canvas content to an image with toDataUrl method supported by the canvas object.
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
var ctx = canvas.getContext("2d"); // Get the context for the canvas.
var myImage = canvas.toDataURL("image/png"); // Get the data as an image.
}
var image = document.getElementById("image"); // Get the image object.
image.src = myImage;
As regarding the second task, after you saved the canvas to an image you can upload the resulted image into the database by using an ajax call. Here is a simple example for how to use it:
$.ajax({
url: "upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
document.getElementById("response").innerHTML = res;
}
});
For a full example see these articles:
http://net.tutsplus.com/tutorials/javascript-ajax/uploading-files-with-ajax/
http://coursesweb.net/ajax/upload-images
回答2:
You would probably need to use JavaScript and maybe PHP. I am not proficient in both of those so I can't help you, but you should look up tutorials on how to make a database on your website.
回答3:
i think you might be interested to have a look on the html5 file api :
http://updates.html5rocks.com/2012/08/Integrating-input-type-file-with-the-Filesystem-API
It would allow you to deal with your issue with no server-side code.
(Rq : this will not solve all your issues.)
来源:https://stackoverflow.com/questions/15039316/save-a-html-canvas-image