How to force the canvas fabricJS to refresh

寵の児 提交于 2020-02-07 03:57:10

问题


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


回答1:


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>


来源:https://stackoverflow.com/questions/57981400/how-to-force-the-canvas-fabricjs-to-refresh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!