1. ホーム
  2. javascript

[解決済み] SVG要素の幅・高さを取得する

2023-01-22 09:46:36

質問

の寸法を取得する適切な方法は何ですか? svg 要素の寸法を取得する適切な方法は何ですか?

http://jsfiddle.net/langdonx/Xkv3X/

Chrome 28です。

style x
client 300x100
offset 300x100

IE10です。

stylex 
client300x100 
offsetundefinedxundefined 

FireFox23です。

"style" "x"
"client" "0x0"
"offset" "undefinedxundefined"

には幅と高さのプロパティがあります。 svg1 には幅と高さのプロパティがありますが .width.baseVal.value は、要素にwidthとheight属性を設定した場合のみ設定されます。


フィドルはこんな感じです。

HTML

<svg id="svg1" xmlns="http://www.w3.org/2000/svg" version="1.1">
    <circle cx="50" cy="50" r="40" stroke="black" stroke-width="1" fill="red" />
    <circle cx="150" cy="50" r="40" stroke="black" stroke-width="1" fill="green" />
    <circle cx="250" cy="50" r="40" stroke="black" stroke-width="1" fill="blue" />
</svg>

JS

var svg1 = document.getElementById('svg1');

console.log(svg1);
console.log('style', svg1.style.width + 'x' + svg1.style.height);
console.log('client', svg1.clientWidth + 'x' + svg1.clientHeight);
console.log('offset', svg1.offsetWidth + 'x' + svg1.offsetHeight);

CSS

#svg1 {
    width: 300px;
    height: 100px;
}

どのように解決するのですか?

getBBox関数を使用します。

http://jsfiddle.net/Xkv3X/1/

var bBox = svg1.getBBox();
console.log('XxY', bBox.x + 'x' + bBox.y);
console.log('size', bBox.width + 'x' + bBox.height);