Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
995 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 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...