When you draw something, the image is redrawn by the script. Because you commented out that line, the old image is not cleared and now there are many stacked images. the script works and you are drawing transparent lines, but there appears many stacked layers, so the the transparent becomes almost opaque.
You don't need to comment that line to be able to import or save sketch's content. Inside the function, "this.actions" stores all user moves. You should only save it in a database, maybe as json, and then load it at beginning and call to draw.
To make this to take really part of Sketch, we'll add some funtions to sketch script.
Before Sketch.prototype.download
, add this function:
Sketch.prototype.export = function() {
$.post('yourfile.php', { data: JSON.stringify(this.actions) }, function (message_back) { alert(message_back); });
};
It converts all the actions to JSON and the POST to yourfile.php
as $_POST["data"]
, and alerts on the screen what you will print out in yourfile.php
. In yourfile.php
you should save $_POST["data"]
on your server o inside a database.
Now, add this before if ($(this).attr('data-download')) {
(you can find this at 3-4 lines before the new added function):
if ($(this).attr('data-export') != undefined) {
sketch.export();
}
That will help you to make the export as simple as to download the resulted image (like data-download
, but data-export
):
<a href="#the_id_of_canvas_here" data-export=''>Save your drawing.</a>
Now, let's build the import functionality:
Add these lines after this.action = [];
(you can find it around line 48):
if ($(this.canvas).attr('data-actions') != undefined) {
// Load json and parse it
this.actions = JSON.parse($(this.canvas).attr('data-actions'));
// Redraw image by using the data
this.redraw();
}
It gets the data from data-actions
attribute of canvas
element and parses it from json, adds the actions at the list of actions of the new image, and then draw the image.
Now, you just add data-actions='HERE COMES THE JSON WHICH YOU SAVED ON THE SERVER ON DB'
to the canvas (Eg: <canvas id="the_id_of_canvas_here" data-actions='HERE COMES THE JSON WHICH YOU SAVED ON THE SERVER ON DB' width="300" height="300"></canvas>
).
Note: when you save the $_POST["data"]
inside a file or database, don't forget to sanitize this (Fastest way to check if a string is JSON in PHP? and Sanitize JSON with php).