SVGの座標やサイズを取得する便利関数"getBoundingClientRect()"

2018年10月8日

Javascript SVG テクノロジー プログラミング

ここ最近、WEBページコーディングで、SVGコントロールをする場面が増えてきました。 デザイン重視のWEBページアニメーションを行なったり、グラフツールのインタラクティブ操作をする場合など、svgオブジェクトの座標やサイズをその場で取得したい場合に、そのエレメントの属性取得をするだけでは機能的に足りていない場合があります。 gタグなどは、下層のオブジェクトサイズに依存したサイズになってしまいますが、通常のエレメントのようにoffsetWidthなどでサイズ取得ができません。 そんな時は"getBoundingClientRect()"関数を使うことで便利にサイズや座標が取得できます。

getBoundingClientRect()の使い方

svgオブジェクトは、通常的なHTMLエレメントのような情報取得ができません。 主に、サイズと座標に関しては、以下のようにgetBoundingClientRect()を使って情報取得をしましょう。 <html> <head> <title>getBoundingClientRect</title> <style> #svg1{ position:absolute; top:100px; left:100px; } </style> </head> <body> <svg id="svg1" width="100" height="100" id="test_1" version="1.1"> <g class="svg1-g"> <rect x="10" y="10" width="80" height="80" fill="skyblue" stroke="blue" stroke-width="4"> </rect> <rect x="10" y="10" width="40" height="40" fill="tomato" rx="8" ry="8" transform="translate(50 10) rotate(45)"></rect> </g> </svg> <script type="text/javascript"> var svg1g = document.querySelector("#svg1 .svg1-g"); console.log(svg1g.getBoundingClientRect()); console.log(svg1g.offsetLeft); console.log(svg1g.offsetWidth); </script> </body> </html> DOMRect bottom: 190 height: 80 left: 110 right: 190 top: 110 width: 80 x: 110 y: 110 undefined undefined offsertLeftとoffsetWidthの値が"undefined"になっているのがわかりますが、"getBoundingClientRect()"の値ではバッチリ取得できています。

通常のinlineオブジェクトにも使える

getBoundingClientRect()関数は、HTMLのエレメントに対しても使用できます。 ただし、HTMLエレメントは、offsetホニャララでだいたい値が取得できるのですが、最も便利に使えるのは、left,topが絶対座標で取得できるという点です。 offsetLeftとoffsetTopは、上位エレメント内での座標を取得するだけで、絶対座標の取得は、階層を遡って座標を他仕込んでいかなければいけません。 下記のサンプルソースでご確認ください。 <html> <head> <title>getBoundingClientRect</title> <style> #test{ border:1px solid red; position:relative; top:100px; left:100px; width:100px; } #test .object-1{ border:1px solid blue; display:block; margin:10px; } #test .object-2{ border:1px solid green; display:inline; margin:10px; } </style> </head> <body> <div id="test"> <div class="object-1">object-1</div> <div class="object-2">object-2</div> </div> <script type="text/javascript"> var obj1 = document.querySelector("#test .object-1"); var obj2 = document.querySelector("#test .object-2"); console.log(obj1.getBoundingClientRect()); console.log(obj1.offsetLeft); console.log(obj1.offsetWidth); console.log(obj2.getBoundingClientRect()); console.log(obj2.offsetLeft); console.log(obj2.offsetWidth); </script> </body> </html> [Log] DOMRect (index.html, line 34) bottom: 139 height: 20 left: 119 right: 199 top: 119 width: 80 x: 119 y: 119 [Log] 10 (index.html, line 35) [Log] 80 (index.html, line 36) [Log] DOMRect (index.html, line 38) bottom: 168 height: 20 left: 119 right: 173.421875 top: 148 width: 54.421875 x: 119 y: 148 [Log] 10 (index.html, line 39) [Log] 55 (index.html, line 40) ちなみに余談ですが、サンプルのようにmarginを設置すると、それも座標に反映されるようです。 あくまでエレメントの本体座標という事を認識していれば大丈夫ですね。

このブログを検索

ごあいさつ

このWebサイトは、独自思考で我が道を行くユゲタの少し尖った思考のTechブログです。 毎日興味がどんどん切り替わるので、テーマはマルチになっています。 もしかしたらアイデアに困っている人の助けになるかもしれません。