简体   繁体   中英

fabric js load single objects to canvas from mysql database

I have a canvas that lives on top of a video. When a user pauses the video they are able to add fabricjs objects to the canvas. When an object is added to the canvas it is saved to a table in a mysql database as JSON.

When the user clicks a button it will query the mysql database for records and return via ajax the objects for each record in an array.

As it loops through this array I want fabricjs to render each object one at a time until all objects have been rendered.

I have tried using :

canvas.loadFromJSON(rData, canvas.renderAll.bind(canvas), function(o, object) {
  fabric.log(o, object);
});

It will load all objects but clears the canvas before each load and will only display the last object.

I have tried the example here:

http://codepen.io/Kienz/pen/otyEz but cannot seem to get it to work for me. I have also tried http://jsfiddle.net/Kienz/bvmkQ/ but cannot see what is wrong.

So I have come to the experts! I appreciate all and any help. Thank you.

Here is my table in mysql wth 2 records:

CREATE TABLE IF NOT EXISTS `telestrations` (
  `id_telestration` int(11) NOT NULL AUTO_INCREMENT,
  `object` longtext NOT NULL,
  PRIMARY KEY (`id_telestration`),
  UNIQUE KEY `id_telestration` (`id_telestration`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=65 ;

--
-- Dumping data for table `telestrations`
--

INSERT INTO `telestrations` (`id_telestration`, `object`) VALUES
(63, '{"objects":[{"type":"i-text","originX":"left","originY":"top","left":161.05,"top":359.29,"width":69.3,"height":20.97,"fill":"#e6977e","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","fillRule":"nonzero","globalCompositeOperation":"source-over","text":"AAAAAA","fontSize":16,"fontWeight":"bold","fontFamily":"arial","fontStyle":"","lineHeight":1.16,"textDecoration":"","textAlign":"left","textBackgroundColor":"","styles":{"0":{"1":{},"2":{},"3":{},"4":{},"5":{}}}}],"background":""}'),
(64, '{"objects":[{"type":"i-text","originX":"left","originY":"top","left":463.68,"top":353.84,"width":69.3,"height":20.97,"fill":"#20f20e","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","fillRule":"nonzero","globalCompositeOperation":"source-over","text":"BBBBBB","fontSize":16,"fontWeight":"bold","fontFamily":"arial","fontStyle":"","lineHeight":1.16,"textDecoration":"","textAlign":"left","textBackgroundColor":"","styles":{"0":{"1":{},"2":{},"3":{},"4":{},"5":{}}}}],"background":""}');

Here is my php file:

$teles = Telestration::getTeleByVideo();

$objArray = array();
foreach($teles as $tele){
    $obj = $tele->getValueEncoded('object');
    $objArray[] = $obj;
}
echo json_encode($objArray);

Here is my JavaScript:

document.getElementById("get_json").onclick = function(ev) {    
  $.ajax({
    url: 'getTelestrations.php',
    data: dataString,
    type: 'POST',
    dataType:"json",
    success: function(data){
      for (var i = 0; i < data.length; i++) {
        rData = data[i].replace(/&quot;/g, '\"');
        //Do something
        canvas.loadFromJSON(rData, canvas.renderAll.bind(canvas), function(o, object) {
          fabric.log(o, object);
        }); 
      }
    }
  }); 
}

Hello inside your success function use instead of canvas.loadFromJSON , the fabric.util.enlivenObjects() funtion, like this:

 //inside the success function, you get the results data from the server and loop inside the items, allright if you have only one object but use      loop for more.
   results.data.forEach(function (object) {
       var tmpObject = JSON.parse(object.table_data);

       fabric.util.enlivenObjects([tmpObject], function (objects) {
             var origRenderOnAddRemove = canvas.renderOnAddRemove;
             canvas.renderOnAddRemove = false;
             console.log(objects);
             objects.forEach(function (o) {
                     canvas.add(o);
                     console.log(o);
              });

            canvas.renderOnAddRemove = origRenderOnAddRemove;
            canvas.renderAll();
         });//end enlivenObjects
    });//end data.forEach

Hope this helps, good luck

I was able to figure out how to load each object. It turns that the json returned from my mysql was not "workable" for fabricjs. I had to clean my json and then the objects would load.

I only made changes to my javascript:

    $.ajax({
        url: 'getTelestrations.php',
        data: dataString,
        type: 'POST',
        dataType:"json",
        success: function(data){
            for (var i = 0; i < data.length; i++) {
                //clean results for json
                json_result = data[i].replace(/&quot;/g, '\"');             //remove quotes from entire result  
                json_clean = json_result.replace(/"objects"/, 'objects');       //remove quotes around first object
                jsonObj = JSON.parse(JSON.stringify(json_clean));               // parse the entire result
                jsonobj2 = eval('(' + jsonObj + ')');
                // Add object to canvas
                var obj = new fabric[fabric.util.string.camelize(fabric.util.string.capitalize(jsonobj2.objects[0].type))].fromObject(jsonobj2.objects[0]); 
                canvas.add(obj); 
                canvas.renderAll();
            }
        }
    }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM