Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FabricJS Canvas Coordinates on Touch

I am using Fabricjs package with events to get attempt to capture user coordinates when they tap the canvas.

This is the code:

Html

<div id="c-wrapper">
      <canvas id="c"></canvas>
</div>

Javascript

var canvas = new fabric.Canvas("c");
canvas.on({
    "mouse:down": function (o) {
            var pointer = canvas.getPointer(o.e);
            console.info("Mouse Coords: "+pointer.x+" "+pointer.y);
    },
    "touch:longpress": function (ev) {
            console.info("Touch Coords: "+ev.self.x+" "+ev.self.y);
    },
});

When i load the page in responsive mode (both Chrome and Safari as well as device emulator) and test the touch feature i get coordinates that are incredibly different.

e.g.

Console output:
Canvas of size 2835 x 2004;

Mouse Coords: 1475 x 1220
Touch Coords: 470 x 388

They are very different results as you can see.

How can i get the actual coordinates of fabric Canvas object when user does a longpress touch event?

like image 568
Aeseir Avatar asked Jan 28 '26 15:01

Aeseir


2 Answers

This will get you the current position.

let e = event.e.touches ? event.e.touches[0] : event.e;
canvas.getPointer(e)
like image 139
Exlord Avatar answered Jan 31 '26 04:01

Exlord


 canvas.on('touch:drag', function(e){
let touch = e.e.touches ? e.e.touches[0] : e.e;
   TouchposX=canvas.getPointer(touch).x
   TouchposY=canvas.getPointer(touch).y
}

Credit to Exlord for helping me figure it out

like image 29
Darren Zou Avatar answered Jan 31 '26 04:01

Darren Zou



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!