0

I want to save and retrieve HTML 5 canvas that I have drawn using Fabric.js, a JavaScript library, into MySQL table using PHP that has a field namely cnvs_obj of BLOB type. I have seen a lot of tuts and Q/A sessions but none has step by step way of teaching. How can I do this, would be very much thankful to you. Here is my canvas example. EDIT: Here is my complete code:

<canvas id="c" style="border:1px solid black;" width="500px" height="300px" ></canvas>
<button onclick="myFunction()" id="btn2">Click me</button>
<script type="text/javascript" src="fabric.min.js"></script>
<script type="text/javascript">
var canvas = new fabric.Canvas('c');
$(function () {     
    //canvas.stateful = true;
    var wel = new fabric.Text('Welcome to FabricJs', {
        fontFamily: 'Delicious_500',
        backgroundColor: 'red',
        left: 80, 
        top: 100 
    });
    canvas.add(wel);
});
canvas.renderAll();
function myFunction() {
    console.log(JSON.stringify(canvas));
    var str_json = JSON.stringify(canvas);
    // send JSON to PHP
    $.ajax({
        type: 'POST',
        url: 'hallo_json.php',
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: { hallo_str: JSON.stringify(str_json) },

    });     
    alert(str_json);

}

</script>

Here is PHP code:

<?php
header('Content-type: text/html');
print_r(json_decode($_POST['str_json']));

Now I can generate JSON, but error 200 arises. I don't where is the error.

Badar
  • 1,430
  • 1
  • 15
  • 19
  • I just can't access str_json variable on in php page. I just want to know if there is any other way doing it. – Badar Apr 10 '15 at 19:26

2 Answers2

0

You can use canvas method toDataUrl. It returns string with data type and format followed by base64 encoded image data. This data you can send to server to decode and save as image.

CyberGuy
  • 2,783
  • 1
  • 21
  • 31
0

If you "want to save and retrieve HTML 5 canvas that I have drawn using Fabric.js", then JSON is fine, by passing JSON between client and server as Text string, you can easily to restore/save the canvas content by loadFromJSON/toJSON, or loadFromDataLessJSON/toDatalessJSON.

By BLOB, it is just saving string to binary format, it won't have issue to do with string in PHP.

In your code, you just want to save all canvas to a JSON string, by that, as there is no native way in browser to build canvas and its content from the JSON string, you will have to build your own method to restore canvas content.

// add Text here, state A
...

// export to json
var json = JSON.stringify(canvas.toJSON());

// add another Tex here, state B
...

// here canvas will go back to the state A
// because it will load JSON data from state A and restore that state
canvas.clear();
canvas.loadFromJSON(JSON.parse(json), canvas.renderAll.bind(canvas));
Tom
  • 4,612
  • 4
  • 32
  • 43