FabricJS canvas "stuck" after adding items

I am fabric.js application using fabric.js and fabric.js experiencing really strange behavior. I add both images and text instances using regular fabric.Canvas (not fabric.StaticCanvas ) and cannot move or resize these elements after adding. I added only a couple of types. The main functionality is wrapped in a callback tied to the click event on a button, but the functionality of the main structure looks something like this (simplified, but almost the same as for the code associated with the network):

 <canvas id="myCanvas" height=600 width=800></canvas> <input id="addStuff" type="button" value="Add!" /> .... var canvas = new fabric.Canvas('myCanvas'); canvas.renderOnAddition = true; $(function(){ $('#addStuff').on('click', function(e) { var text = new fabric.Text("Hello, world", { top : 100, left : 100, fontSize : 12, fontFamily : 'Delicious_500' }); text.hasControls = false; canvas.add(text); fabric.Image.fromURL('./img/pic.png', function(img) { var imgX = img.set({ top: 200, left: 100, }); canvas.add(imgX); }); canvas.renderAll(); }); }); 

The above code displays elements well, but they cannot be changed or moved, and act statically. It is strange that if I open and close the chrome dev panel (F12 panel or [Ctrl / CMD] + SHIFT + I twice), the canvas restores functionality and everything works again . I also have some server-side stuff (this is just a mock example of what I'm doing), but I have no idea how to further trace this to this strange behavior. I am using the latest code (built from github repo). Thoughts?

+6
source share
2 answers

It is possible that the internal canvas offset is not being updated properly. Something on the page could resize / position, making the canvas positioned elsewhere than the one that was during initialization. Try calling canvas.calcOffset() after calling renderAll() or after adding these objects.

The reason calcOffset not called in renderAll for performance reasons. renderAll is a redraw of the entire canvas. This happens every time something changes on the canvas, and the canvas needs to be redrawn. As you can imagine, it is often called (sometimes dozens of times per second), and it would be rather wasteful to calculate a new offset every time a redraw occurs.

Also consider that in most cases the position of the canvas does not change throughout the life of the pages. This probably happens quite rarely. Mostly during page load.

In a highly dynamic environment - where the canvas often changes position - you can solve the offset problem by explicitly calling calcOffset() .

+22
source

I had the same problem, in addition to kangax's solution, in a VERY extreme environment, you can make it recalculate the offset at any time when rendering occurs with the event.

canvas.on('after:render', function(){ this.calcOffset(); });

+7
source

Source: https://habr.com/ru/post/918462/


All Articles