簡體   English   中英

如何使用 d3js 獲取 svg 元素的寬度?

[英]How do I get the width of an svg element using d3js?

我正在使用 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>

但它返回了這個錯誤:

未捕獲的類型錯誤:無法調用 null 的方法“getPropertyValue”

我認為, svg 變量是一個空數組。

如何使用 d3js 獲取 svg 元素的寬度?

<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 元素后放置您的腳本,一切都會好起來的。

如果您有一個帶有 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());

哪些是數字,可用於數學表達式

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

var w = parseInt(svg.style("width"), 10);
var h = parseInt(svg.style("height"), 10);

嘗試使用 svg.attr("width")。 它只是給出一個普通的數字字符串。

如果此 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") 返回一個字符串。

除非您初始化屬性(寬度)的值,否則您最終會得到值“auto”,我建議改為使用以下值。

d3element.getBoundingClientRect().width;

var element = d3.select('.ClassName').node();
element.getBoundingClientRect().width;

// 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)

在這一天,這對我有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM