简体   繁体   中英

Mouse offset in canvas [fabric.js]

I've read 3-5 topics about mouse offset, but i still can't get where is the mess.

In my case everything works fine in 60%. In other 40% mouse is offset. Demo here .

Sometimes object position doesn't relate to mouse behavior. (IE & Chrome have the bigest mess)

I've tried to edit stylesheets and parent div but nothing. The worst thing: i don't see any regularity. I will be greatful for any help.

You can do this:

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

I only do this after I create canvas. This is interim call when there is no resize event. That is when bug appears.

Due to positioning of other elements on the page the canvas offset value may change.

You just needed to call canvas.calcOffset() after adding an element in the canvas that caused the problem or after calling the canvas.renderAll() method in the code.

This offset issue occurs whenever the canvas is moved within the HTML document. For example, if you add an element of 10px in height above the canvas, after the canvas is first rendered, your objects will be offset by 10px. Add this code whenever the canvas is repositioned within the HTML doc, and it should recalculate the mouse interactivity:

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

Fabric.js automatically calls this method whenever the window is resized, which is why you don't see the issue on that event.

It is unbelievable! I've fixed the bug. You will never believe me...

In the top of the page it was code like:

<div class="logo">
<a href="/"><img src="logo.png" alt="" /></a>
</div>

This code has no reasonable relation to canvas. This class have simple css: {float: left; margin: 10px 0 0 0;} {float: left; margin: 10px 0 0 0;}

But for some reason this code forced mouse offset in canvas. I remade this code like:

<div class="logo">
<a href="/" class="logoHref"></a><!--- image is in css bg --->
</div>

... and now everything thinks to work fine.

I dont see any corelation between these events but the fact is the fact. That was a damn hard day for me...

Offset positioning of an object within a canvas is most likely caused by the original coordinates of the canvas and child objects being changed by DOM manipulation.

A simple solution I found is to make sure I set the coordinates of any object that I add to the canvas immediately after adding it. For example, if you assume the object is an image, you would do the following:

var canvas = new fabric.Canvas(); 
var image = new Image();

canvas.add( image );
image.center() // Optional if you wish the object centered on canvas
image.setCoords();

Hope this helps. Good luck!

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