Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

fabricjs - How to get polygon points in Fabric.js

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m 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
  };
});

Let's check how this looks:

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

enter image description here

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...