简体   繁体   English

如何设置 D3.js svg 的背景颜色?

[英]How to set the background-color of a D3.js svg?

I'm not very familiar in styling D3.js SVG's.我对 D3.js SVG 的样式不是很熟悉。 I create a collapsible tree and will provide an option to download this tree as SVG/PDF/PNG.我创建了一个可折叠的树,并将提供一个选项来将这棵树下载为 SVG/PDF/PNG。 This works great but the background-color of the resulting files is always transparent.这很好用,但生成的文件的背景颜色总是透明的。 Is there a possibility to create the D3 SVG with a specific background-color?是否有可能创建具有特定背景颜色的 D3 SVG? I used this example for my work:我在我的工作中使用了这个例子:

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

Thank you!谢谢!

Just add a <rect> as the first painting order item that displays the colour you want. 只需添加<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 + ")");

You can use the SVG as another HTML component, you can set its CSS properties: 您可以将SVG用作另一个HTML组件,您可以设置其CSS属性:

For instance, on creating the svg, you set a class: 例如,在创建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");

In your CSS you can define the property: 在CSS中,您可以定义属性:

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

Use .style() to control the CSS properties:使用 .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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM