代码之家  ›  专栏  ›  技术社区  ›  Aenaon

选择(“svg”)—两个备选方案之间的区别

  •  1
  • Aenaon  · 技术社区  · 7 年前

    我对此有点困惑。我以为它们是等价的表达,但显然不是。下面是做饼图的一段代码的起始行。这样可以很好地工作,并且转换会将图表移动到svg的中心

    var width = 280,
        height = 200,
        radius = Math.min(width, height) / 2;
    
    var svg = d3.select("#pie")
        .select("svg")
        .attr("width", width)
        .attr("height", height)
        .append("g")
        .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")"); 
    

    但是我试着移动 width height 宽度 高度

    <div class="chart-stage" id="pie">
          <svg width="280" height="200"></svg>
    </div>
    

    我想我一定是把svg链接搞错了

    var svg = d3.select("#pie")
                .select("svg")
    
    var width = +svg.attr("width"),
        height = +svg.attr("height")
    
    var radius = Math.min(width, height) / 2;
    
    svg.attr("width", width)
        .attr("height", height)
        .append("g")
        .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")"); 
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Andrew Reid    7 年前

    svg g 具有变换的元素。在第二个 svg格式 指选定的 元素。 svg格式 svg.append() 将附加一个兄弟姐妹 :

    var svg = d3.select("#pie")       // return a selection of the element with id pie
        .select("svg")                // return a selected of the svg
        .attr("width", width)         // return the same svg
        .attr("height", height)       // return the same svg
        .append("g")                  // return a selected g element
        .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");  // return the selected g element.
    

    在这里 svg格式 元素。

    var svg = d3.select("#pie")   // return a selection of the element with id pie
                .select("svg");    // return a selection of the svg
    

    svg格式 -初始链接完成后,后续操作: svg.attr().append() 不要更改变量的定义。

    svg格式 变量作为子对象的选择

    var svg = d3.select("#pie")
            .select("svg")
    
    var width = +svg.attr("width"),
        height = +svg.attr("height")
    
    svg = svg.append("g")
        .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")"); 
    

    不过,把这个变量称为 因为这是一个选择 svg格式 .