Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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:

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

Thank you!

like image 620
user3017615 Avatar asked Nov 22 '13 10:11

user3017615


People also ask

Does SVG have background color?

The SVG background is used to draw any kind of shape, set any color you want by the set property. The below examples illustrates the concept of SVG set background-color more specifically. The SVG allowed the CSS background sizing, position, and much more complex property.

Does D3 js use SVG?

To create SVG using D3. js, let us follow the steps given below. Step 1 − Create a container to hold the SVG image as given below. Step 2 − Select the SVG container using the select() method and inject the SVG element using the append() method.


2 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 + ")"); 
like image 128
Robert Longson Avatar answered Sep 19 '22 01:09

Robert Longson


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; } 
like image 20
Ismael Hasan Avatar answered Sep 22 '22 01:09

Ismael Hasan