Search code examples
d3.jssvgcolorsfill

Setting svg fill attribute in Javascript


Beginner's question. Why does the color variable color.svg not work when I try to change my svg attribute? Everything else works: the other colors (for circles added later), as well as the size of the svg (sizing taken from here).

Constants:

// colors
var color = {svg: "black", 
             drop0: "rgba(204, 204, 255, 1)",
             drop1: "orange"};

// margins
var margin = {top: 20, right: 10, bottom: 20, left: 10};
var width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

Now I make an svg and try set attributes.

// svg
var svg = d3.select("body").append("svg")
   .attr({width: width + margin.left + margin.right,
          height: height + margin.top + margin.bottom,
          fill: color.svg})
   .append("g")
   .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

// followed by stuff about adding shapes, etc, which work

I would prefer not to set it in CSS. No errors are thrown on the browser. I've commented out everything but these lines, and the svg is still not colored black.


Solution

  • SVG's container has not attr "fill", instead it has "style". Just replace it like so:

    var color = {
      svg: "black",
      drop0: "rgba(204, 204, 255, 1)",
      drop1: "orange"
    };
    
    // margins
    var margin = {
      top: 20,
      right: 10,
      bottom: 20,
      left: 10
    };
    var width = 960 - margin.left - margin.right,
      height = 500 - margin.top - margin.bottom;
    //Now I make an svg and try set attributes.
    
    // svg
    var svg = d3.select("body").append("svg")
      .attr("width", 900)
      .attr("height",600)
      .style("background-color", color.svg)  //  <---- HERE
      .append("g")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
    

    Here de jsfiddle

    and check this: https://css-tricks.com/cascading-svg-fill-color/