Kenzo
Kenzo

Reputation: 1837

How to force the canvas fabricJS to refresh

I am currently using fabricJS(version 1.4.0) canvas and i have 100 objects that i manually add on the canvas, however objects only appear when i click anywhere on the canvas, is there a way of forcing the canvas to refresh itself ? Here is kind of scenario i have if it can help somehow.

  ....
 initComplete: function (settings, json) {

   let clients = json;
   if(clients.length !== 0)
   {
       //clients is an array of length 100
       for (client of clients)
        {
             let icone = new Image;
              if (client.ProfileId !== '')
              {

                   //..Codes pour afficher les client wifi sur le canvas
                   client_real_left = (client.MapCoordinate.x * baseWidth) / widthFloor;
                   client_real_top = (client.MapCoordinate.y * baseHeight) / lengthFloor;
                   client_left = client_real_left;
                   client_top = client_real_top;

                   if (client.IconName === 'default.png' || client.IconName === null) {
                        icone.src = '/Icones/wifi.png';
                   }
                   else {
                          icone.src = '/Icones/' + client.IconName;
                        }

                          const wifiClient = new fabric.Image(icone,
                          {

                                    id: client.ProfileId,
                                    class: 'img_wifiClient',
                                    left: (transX + client_left) * canvasFabric.scale,
                                    top: (transY + client_top) * canvasFabric.scale,
                                    selectable: true,
                                    hasBorders: false,
                                    hasControls: false,
                                    padding: 0,
                                    perPixelTargetFind: true,
                                    width: 24,
                                    height: 24,
                                    originX: 'center',
                                    originY: 'center'
                                });


                            canvasFabric.add(wifiClient);

                        }
   } //end if

}

the initComplete is a callback function of jQuery DataTable

Upvotes: 2

Views: 5176

Answers (1)

Durga
Durga

Reputation: 15604

Use image#setSrc and call renderAll on callback method.

DEMO

var canvas = new fabric.Canvas('c',{
  width:400,
  height:400
});
var image = new fabric.Image('');
canvas.add(image);

image.setSrc('https://picsum.photos/200/300',function(){
  image.setCoords();
  canvas.renderAll();
})
canvas{
  border:1px solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.2.0/fabric.js"></script>
<canvas id='c'></canvas>

Upvotes: 2

Related Questions