如何在Fabric.js中获取多边形点

问题描述:

我通过捕获鼠标在画布上的点击然后将这些点传递到fabric.Polygon来绘制多边形.因此,我以这种方式绘制了多个多边形.

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?

我尝试过:

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?

多边形点相对于其中心,因此您可以像这样获得它们的绝对"位置:

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

让我们看看它的外观:

translatedPoints.forEach(function(p) {
  canvas.getContext().strokeRect(p.x-5, p.y-5, 10, 10);
});

我认为这仅在多边形的角度为0(否则也需要旋转"点坐标)时有效.

I think this will only work if polygon's angle is at 0 (otherwise need to "rotate" points coordinates as well).