Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get bounding box of SVG path

I want exactly what this page do

http://codepen.io/netsi1964/full/vNoemp/

I have the path and need to know it's bounding box as a rect element, it's x,y,width and height given code

<path d="M147.5 55.8c-5.8-7.2-13.6-14.4-25.5-14.4-8.4 0-15.4 8.2-27 8.2-9 0-13-7.8-23-7.8C51.4 41.8 31 60.4 31 84.5c0 12.8 4.2 32.5 13.6 49.7C51 146.7 59.4 155 69 155c6.7 0 14.7-6.3 24.2-6.3 8.4 0 16.2 5.6 23.8 5.6 18 0 35-23.5 35-39.3 0-.8-.3-1.4-.3-2v-1c-11.8-6.3-18.2-15.7-18.2-29.3 0-11 4.8-20.5 13.6-26.7l.5-.2zm-53-8.8c13.7-4.2 26.3-14.4 26.3-32 0-1.5-.2-3.3-.4-5.3l-.2-.8C106.4 12.6 94 23.4 94 40.3c0 1.6.2 3.6.6 5.8v.8z" style="translate(0px,-212.47488403320312px) scale(1,1)" >

and know the rect properties

like image 449
rafat mansour Avatar asked Oct 29 '16 03:10

rafat mansour


People also ask

What is the path of an SVG?

The <path> element is the most powerful element in the SVG library of basic shapes. It can be used to create lines, curves, arcs, and more. Paths create complex shapes by combining multiple straight lines or curved lines. Complex shapes composed only of straight lines can be created as <polyline> s.

What is getBBox?

getBBox() method allows us to determine the coordinates of the smallest rectangle in which the object fits. The coordinates returned are with respect to the current SVG space (after the application of all geometry attributes on all the elements contained in the target element).


1 Answers

With pure JavaScript: give your path an ID and get its bounding box using getBBox().

var myPathBox = document.getElementById("myPath").getBBox();
console.log(myPathBox);

Here is a demo:

var myPathBox = document.getElementById("myPath").getBBox();
console.log(myPathBox);
<svg width="400" height="400">
	<path id="myPath" d="M147.5 55.8c-5.8-7.2-13.6-14.4-25.5-14.4-8.4 0-15.4 8.2-27 8.2-9 0-13-7.8-23-7.8C51.4 41.8 31 60.4 31 84.5c0 12.8 4.2 32.5 13.6 49.7C51 146.7 59.4 155 69 155c6.7 0 14.7-6.3 24.2-6.3 8.4 0 16.2 5.6 23.8 5.6 18 0 35-23.5 35-39.3 0-.8-.3-1.4-.3-2v-1c-11.8-6.3-18.2-15.7-18.2-29.3 0-11 4.8-20.5 13.6-26.7l.5-.2zm-53-8.8c13.7-4.2 26.3-14.4 26.3-32 0-1.5-.2-3.3-.4-5.3l-.2-.8C106.4 12.6 94 23.4 94 40.3c0 1.6.2 3.6.6 5.8v.8z" style="translate(0px,-212.47488403320312px) scale(1,1)" >
	</svg>
like image 97
Gerardo Furtado Avatar answered Nov 16 '22 12:11

Gerardo Furtado