How to get polygon points in Fabric.js

耗尽温柔 提交于 2019-11-27 03:38:26

问题


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?


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/19854808/how-to-get-polygon-points-in-fabric-js

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!