Reputation: 33
I am drawing polygon by capturing mouse clicks on canvas and then passing these points to fabric.Polygon
. So, in this manner I'm drawing multiple polygons.
What I need know is, I want to get the mouse co-ordinates (pixel points on canvas) for the polygon which is selected now?
I have tried with:
canvas.getActiveObject().get('points');
But this is giving some negative and some positive values.
So, can u please tell me a way to find out the polygon points?
Upvotes: 3
Views: 9994
Reputation: 435
2025 version based on fabric 6.5.4 (typescript) and @VitaliiBratok answer:
import { Point } from 'fabric';
const transformedPoints: Point[] = polygon
.get('points')
.map((p: Point) => {
return new Point(p.x - polygon.pathOffset.x, p.y - polygon.pathOffset.y);
})
.map((p: Point) => {
return p.transform(polygon.calcTransformMatrix());
});
Upvotes: 0
Reputation: 771
It looks like that from version 2.0 they changed the coordinates of the polygon. Before 2.0 points relative to the center of the polygon; after 2.0 they are absolute to the canvas;
Check out my response to the similar questions https://stackoverflow.com/a/53710375/4681279
Upvotes: 0
Reputation: 39188
Polygon points are relative to its center so you can get their "absolute" position like so:
var polygon = canvas.getActiveObject();
var polygonCenter = polygon.getCenterPoint();
var translatedPoints = polygon.get('points').map(function(p) {
return {
x: polygonCenter.x + p.x,
y: polygonCenter.y + p.y
};
});
Let's check how this looks:
translatedPoints.forEach(function(p) {
canvas.getContext().strokeRect(p.x-5, p.y-5, 10, 10);
});
I think this will only work if polygon's angle is at 0 (otherwise need to "rotate" points coordinates as well).
Upvotes: 11