Send Data to Server using Canvas

351 Views Asked by At

I drow some objects with canvas KineticJS, I tried canvas.toDataURL("image/png"); but i don't know how to get params values when i click on submit button I want send some params to server,

thanks

2

There are 2 best solutions below

1
On
$.ajax({
    type: "POST",
    url: url,
    data: "yourData="+encodeURIComponent(canvas.toDataURL());,


    complete: function (result) {
        //your response
    },
    error: function () {
        //if error occured
    }
});

//Accept your data serverside in your function or method or model according to technology eg in php: -echo($_POST["yourData"]);

0
On

All the objects on the Kinetic.Stage can be serialized into a JSON string:

First, serialize the stage to JSON:

var json = stage.toJSON();

Then that json string can be sent to your server using jquery's ajax method:

$.ajax({
  type: "POST",
  url: "http://yourSite.com/saveTheStage.php",
  data: {stageJSON: stage.toJSON()}
})
.done(function(respond){alert("done: "+respond);})
.fail(function(respond){alert("fail");})
.always(function(respond){alert("always");})

On the server, read the received json and save it to a unique filename (this example uses PHP).

<?php 

if ( isset($_POST["stageJSON"]) && !empty($_POST["stageJSON"]) ) { 

    // get the stage data
    $json = $_POST['stageJSON'];

    // create a filename for the new image
    $file = md5(uniqid()) . '.json';

    // decode the image data and save it to file
    file_put_contents($file, $json);

    // return the filename
    echo $file;

}

?>

Note that stage.toJSON serializes the Kinetic.Stage's properties, but does not save elements that were external to Kinetic.

For example, if your stage has a Kinetic.Image, the Kinetic.Image's properties will be serialized (x,y,etc), but the .png data of the image you injected into the Kinetic.Image will not be serialized.

Therefore is you later de-serialize the stage you must do myImage.setImage to reset the .png data into the re-hydrated Kinetic.Image.

Also note that stage.toJSON will not serialize any javascript variables, so if your LIGHT is a javascript variable, it will not be serialized.

You can add more data to your ajax packet to include LIGHT

data: {
    stageJSON: stage.toJSON(),
    LIGHT: LIGHT
}