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
705 views
in Technique[技术] by (71.8m points)

html - How to get Mid point of <g> tag in svg using javascript

I am working in SVG tags using javascript. I tried to get group tag <g> midpoint in svg. Is it possible to get mid point value of group tag using javascript? Here's my demo group tag <g>

<g id="object_7" transform="translate(573,703) scale(0.5,0.51)" style="pointer-events:inherit">

<path d="m-40,-19l3,-3l74,0l3,3l0,37l-3,3l-74,0l-3,-3l0,-37z" id="uid127" stroke-linejoin="round" stroke-linecap="round" fill="#1e1d19" stroke="#000000"/>

   <path d="m-9,21l4,2l10,0l4,-2" id="uid129" stroke-linejoin="round" stroke-linecap="round" fill-opacity="0" fill="none" stroke="#000"/>

   <path d="m-40,-19l3,-3l74,0l3,3l-77,40l-3,-3l0,-37z" id="uid131" stroke-linejoin="round" stroke-linecap="round" fill-opacity="0.12" fill="#000000"/>

</g>

Here I need to get midpoint point of group tag. I used to get mouse co-ordinates for getting center of x and y position in group tag, but I did not achieve it. Can anyone please guide me?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can get the bounding box of the <g> element by getting a reference to it and calling the function getBBox().

var  bbox = document.getElementById("object_7").getBBox();

Note however that this is the union of all the bounding boxes of the group's children. If the group has a transform, it is not reflected in the bbox value. If you are adding elements to the group, this is probably the one you want.

If you want the bounds of the object in screen space, then you can get the group element's transform and apply it to the centre point you have calculated.

var  ctm = document.getElementById("object_7").getCTM()

// Calculate the centre of the group
var cx = bbox.x + bbox.width/2;
var cy = bbox.y + bbox.height/2;

// Transform cx,cy by the group's transform
var pt = document.getElementById("mysvg").createSVGPoint();
pt.x = cx;
pt.y = cy;
pt = pt.matrixTransform(ctm);

// centre point in screen coordinates is in pt.x and pt.y

Demo here


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

...