36

私は d3js を使用して、以下に示すコードの svg 要素の幅を見つけています。

<script>
    var body = d3.select("body");
    console.log(body);
    var svg = body.select("svg");
    console.log(svg);
    console.log(svg.style("width"));
</script>

<svg class="svg" height="3300" width="2550">
   <image x="0" y="0" height="3300" width="2550" xlink:href="1.jpg"></image>
   <rect class="word" id="15" x="118" y="259" width="182" height="28"
      text="Substitute"></rect>
</svg>

しかし、それはこのエラーを返しました:

キャッチされていない TypeError: null のメソッド 'getPropertyValue' を呼び出せません

svg 変数は null 配列だと思います。

d3jsを使用してsvg要素の幅を取得するにはどうすればよいですか?

4

7 に答える 7

36
<svg class="svg" height="3300" width="2550">
    <image x="0" y="0" height="3300" width="2550" xlink:href="1.jpg"></image>
    <rect class="word" id="15" x="118" y="259" width="182" height="28"
     text="Substitute"></rect>
</svg>

<script>
    var body = d3.select("body");
    console.log(body);
    var svg = body.select("svg");
    console.log(svg);
    console.log(svg.style("width"));
</script>

ブラウザーによって svg 要素が読み込まれた後にスクリプトを配置するだけで問題ありません。

于 2013-10-31T15:23:57.507 に答える
18

id=frame を持つ SVG 要素がある場合...

 frame = d3.select('#frame')
                     .attr('class', 'frame')

            fh = frame.style("height").replace("px", "");
            fw = frame.style("width").replace("px", "");

fh と fw を数式で使用できるようになりました。

jQueryに戻すこともできます

  fw = console.log($("#frame").width());
  fh = console.log($("#frame").height());

これは数値であり、数式で使用できます

于 2014-05-15T18:56:39.993 に答える
4

svg.attr("width") を使用してみてください。単純な数値文字列を与えるだけです。

于 2014-07-23T13:36:46.400 に答える
2

たとえば、この svg が変数に保存されている場合:

var vis = d3.select("#DivisionLabel").append("svg")
    .attr("width", "100%")
    .attr("height", height);

次に、変数を直接使用して、次の方法visで svg の幅を取得できます。

console.log(vis.style("width"));

結果の単位は「px」です。vis.style("width") が文字列を返すことに注意してください。

于 2015-11-12T14:50:15.887 に答える
-1

// HTML

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
        <svg width="950" height="500"></svg>
    <script src="https://d3js.org/d3.v5.min.js"></script>
    <script src="index1.js"></script>
</body>
</html>

//JavaScript

const svg = d3.select('svg');

const width = +svg.attr('width');
const height = +svg.attr('height');
console.log(width)
console.log(height)

現時点では、これが私にとってうまくいくものです。

于 2020-05-19T11:35:44.937 に答える