Wayne Gilliver Wayne Gilliver - 26 days ago 8
Javascript Question

Load From Json fabricJS

I am trying to load an object from a textarea, below shows my code (with the export code) but I can't work out how to loadfromjson. Could anyone help please. I have scoured the internet looking for a similar example, but I cannot find one except the one on the kitchensink json tab.

// to JSON string
$("#canvas2json").click(function(){

canvas.isDrawingMode = false;

if(!window.localStorage){alert("This function is not supported by your browser."); return;}

var json = JSON.stringify(canvas);
//canvas.renderAll();
$("#myTextArea").text(json);

});


// from JSON string
$("#loadJson2Canvas").click(function(){


var jsonLoad = "'" + document.getElementById("myTextArea")+ "'";

//alert(jsonLoad).value;

canvas = window.canvas = new fabric.Canvas('canvas');

canvas.loadFromJSON(jsonLoad, canvas.renderAll.bind(canvas));


});

Answer

The problem in your script is the following statement:

var jsonLoad = "'" + document.getElementById("myTextArea")+ "'";

this not return the content of your textarea, but the DOM element, and so the .toString result. Since you are using jQuery you could do something like

$("#myTextArea").val()

and so:

$(function() {
  var canvas = new fabric.Canvas('c');
  /*
  canvas.add(new fabric.Circle({
    radius: 50,
    left: 0,
    top: 0,
    fill: '#0B61A4'
  }));
  */

  $("#canvas2json").click(function() {
    var json = canvas.toJSON();
    $("#myTextArea").text(JSON.stringify(json));
  });
  $("#loadJson2Canvas").click(function() {
    canvas.loadFromJSON(
      $("#myTextArea").val(),
      canvas.renderAll.bind(canvas));

  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.4/fabric.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id='c' width=300 height=150></canvas>
<br/>
<button id='canvas2json'>canvas2json</button>
<button id='loadJson2Canvas'>loadJson2Canvas</button>
<br/>
<textarea id='myTextArea'></textarea>