【问题标题】:How to set the background-color of a D3.js svg?如何设置 D3.js svg 的背景颜色?
【发布时间】:2013-12-07 05:17:38
【问题描述】:

我对 D3.js SVG 的样式不是很熟悉。我创建了一个可折叠的树,并将提供一个选项来将此树下载为 SVG/PDF/PNG。这很好用,但生成的文件的背景颜色总是透明的。是否有可能创建具有特定背景颜色的 D3 SVG?我在我的工作中使用了这个例子:

http://bl.ocks.org/mbostock/4339083

谢谢!

【问题讨论】:

  • Simply svg {background-color:red;} 似乎对我有用。
  • 将绘图导出为 PDF/PNG 后是否会包含在内?
  • .style("background-color", 'red');
  • @tewathia - 即使您的解决方案有效,它们也不是 w3C 标准(阅读更多 stackoverflow.com/questions/11293026/… 和 w3.org/TR/SVG/styling.html)
  • @geotheory - 请阅读我对 tewathia 的评论

标签: javascript svg d3.js


【解决方案1】:

使用 .style() 控制 CSS 属性:

const svg = d3.create("svg")
              .attr("viewBox", [-width/2, -15, width/1.3, height])
              .attr("width", width)
              .attr("height", height)
              .attr("style", "max-width: 100%; height: auto; height: intrinsic;")
              .attr("font-family", "sans-serif")
              .attr("font-size", 15)
              .style("background", "yellow");

【讨论】:

    【解决方案2】:

    您可以将 SVG 用作另一个 HTML 组件,您可以设置它的 CSS 属性:

    例如,在创建 svg 时,您设置了一个类:

    var svg = d3.select("body").append("svg")
        .attr("width", width + margin.right + margin.left)
        .attr("height", height + margin.top + margin.bottom)
        .attr("class", "graph-svg-component");
    

    在你的 CSS 中你可以定义属性:

    .graph-svg-component {
        background-color: AliceBlue;
    }
    

    【讨论】:

      【解决方案3】:

      只需添加一个<rect> 作为显示您想要的颜色的第一个绘画订单项。

      var svg = d3.select("body").append("svg")
          .attr("width", width + margin.right + margin.left)
          .attr("height", height + margin.top + margin.bottom);
      
      svg.append("rect")
          .attr("width", "100%")
          .attr("height", "100%")
          .attr("fill", "pink");
      
      svg.append("g")
          .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
      

      【讨论】:

      • 如果您需要 svg.selectAll("rect") 条形图,不确定这是否有效?
      • 别那么做,选择更具体的。
      猜你喜欢
      • 2019-06-22
      • 2018-02-09
      • 2015-01-09
      • 1970-01-01
      • 1970-01-01
      • 2010-12-11
      • 2021-12-04
      • 1970-01-01
      • 2023-03-09
      相关资源
      最近更新 更多