Yevgen
Yevgen

Reputation: 1300

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.

Upvotes: 8

Views: 6205

Answers (5)

ImaJedi4ever
ImaJedi4ever

Reputation: 3331

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!

Upvotes: 0

Ashish Kaila
Ashish Kaila

Reputation: 557

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.

Upvotes: 16

M -
M -

Reputation: 28472

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.

Upvotes: 2

Ghost-Man
Ghost-Man

Reputation: 2187

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.

Upvotes: 3

Yevgen
Yevgen

Reputation: 1300

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;}

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...

Upvotes: 1

Related Questions