I'm not very familiar in styling D3.js SVG's. I create a collapsible tree and will provide an option to download this tree as 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? I used this example for my work:

Thank you!

5

3 Answers

Just add a <rect> as the first painting order item that displays the colour you want.

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 + ")"); 
3

You can use the SVG as another HTML component, you can set its CSS properties:

For instance, on creating the svg, you set a class:

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:

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

Use .style() to control the CSS properties:

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"); 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.