0

I created a bar chart in D3.js and filled the bars with <pattern>. Now, I want to save the bar chart to a .svg file. I followed the codes from this question. However, I can only save a bar chart without filling. I think the problem is that the <pattern> is not a dom element, so it cannot be exported in this way.

Do you know how to solve this and save the bar chart with pattern to a svg file?

Here is my code. You can click the Save SVG button to save the svg file.

var btn = document.getElementById("btn");
var rotateRect = document.getElementById("rotateRect");
  var data = [{ year: '2001', value:10 },
            { year: '2002', value:30 },
            { year: '2003', value:20 },
           ]
var svg = d3.select("svg#barchart"),
            margin = 200,
            width = svg.attr("width") - margin,
            height = svg.attr("height") - margin


var xScale = d3.scaleBand().range([0, width]).padding(0.4),
            yScale = d3.scaleLinear().range([height, 0]);

var g = svg.append("g")
            .attr("transform", "translate(" + 100 + "," + 100 + ")");

    

        xScale.domain(data.map(function(d) { return d.year; }));
        yScale.domain([0, d3.max(data, function(d) { return d.value; })]);

        g.append("g")
         .attr("transform", "translate(0," + height + ")")
         .call(d3.axisBottom(xScale));

        g.append("g")
         .call(d3.axisLeft(yScale).tickFormat(function(d){
             return d;
         }).ticks(10));

        g.selectAll(".bar")
         .data(data)
         .enter().append("rect")
         .attr("class", "bar")
         .attr("x", function(d) { return xScale(d.year); })
         .attr("y", function(d) { return yScale(d.value); })
         .attr("width", xScale.bandwidth())
         .attr("height", function(d) { return height - yScale(d.value); })
         .attr('stroke', "black")
         .attr('stroke-width', '1')
         // .attr("fill", "white")
         .attr("fill", function(d,i) { return  "url(#pattern" + (i+1) +")"});

btn.onclick = function(){
  console.log("save svg")
  var svgData = $("#barchart")[0].outerHTML;
var svgBlob = new Blob([svgData], {type:"image/svg+xml;charset=utf-8"});
var svgUrl = URL.createObjectURL(svgBlob);
var downloadLink = document.createElement("a");
downloadLink.href = svgUrl;
downloadLink.download = "new.svg";
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}
#rotateRect{
  transform:rotate(45deg);
    transform-origin: center center;
    transform-box: fill-box;
}
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>

<svg id = "barchart" width="600" height="500"></svg>

<svg width="0" height="0">
    
    <defs>
        <pattern id="pattern1"
                 x="0" y="0" width="20" height="20"
                 patternUnits="userSpaceOnUse" >
      
<!--             <circle cx="10" cy="10" r="10" style="stroke: none; fill: #0000ff" /> -->
          <rect id="rotateRect" x="5" y = "5" width = "10" height = "10" />
      
        </pattern>
      </defs>
    
      <defs>
        <pattern id="pattern2"
                 x="0" y="0" width="20" height="20"
                 patternUnits="userSpaceOnUse" >
      
            <circle cx="10" cy="10" r="5" style="stroke: none; fill: #0000ff" />
      
        </pattern>
      </defs>
    
      <defs>
        <pattern id="pattern3"
                 x="0" y="0" width="20" height="20"
                 patternUnits="userSpaceOnUse" >
      
            <circle cx="10" cy="10" r="3" style="stroke: none; fill: #0000ff" />
      
        </pattern>
      </defs>
 
</svg>

<button id="btn">Save SVG</button>

What I want to get is a svg file looks like: expected result

What I got from my current code is a svg file looks like:current result

Thank you in advance.

Tingying He
  • 137
  • 7

1 Answers1

2

Put the patterns in the same svg as the barchart I.e. use one svg element, not two.

var btn = document.getElementById("btn");
var rotateRect = document.getElementById("rotateRect");
  var data = [{ year: '2001', value:10 },
            { year: '2002', value:30 },
            { year: '2003', value:20 },
           ]
var svg = d3.select("svg#barchart"),
            margin = 200,
            width = svg.attr("width") - margin,
            height = svg.attr("height") - margin


var xScale = d3.scaleBand().range([0, width]).padding(0.4),
            yScale = d3.scaleLinear().range([height, 0]);

var g = svg.append("g")
            .attr("transform", "translate(" + 100 + "," + 100 + ")");

    

        xScale.domain(data.map(function(d) { return d.year; }));
        yScale.domain([0, d3.max(data, function(d) { return d.value; })]);

        g.append("g")
         .attr("transform", "translate(0," + height + ")")
         .call(d3.axisBottom(xScale));

        g.append("g")
         .call(d3.axisLeft(yScale).tickFormat(function(d){
             return d;
         }).ticks(10));

        g.selectAll(".bar")
         .data(data)
         .enter().append("rect")
         .attr("class", "bar")
         .attr("x", function(d) { return xScale(d.year); })
         .attr("y", function(d) { return yScale(d.value); })
         .attr("width", xScale.bandwidth())
         .attr("height", function(d) { return height - yScale(d.value); })
         .attr('stroke', "black")
         .attr('stroke-width', '1')
         // .attr("fill", "white")
         .attr("fill", function(d,i) { return  "url(#pattern" + (i+1) +")"});

btn.onclick = function(){
  console.log("save svg")
  var svgData = $("#barchart")[0].outerHTML;
  console.log(svgData);
var svgBlob = new Blob([svgData], {type:"image/svg+xml;charset=utf-8"});
var svgUrl = URL.createObjectURL(svgBlob);
var downloadLink = document.createElement("a");
downloadLink.href = svgUrl;
downloadLink.download = "new.svg";
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}
#rotateRect{
  transform:rotate(45deg);
    transform-origin: center center;
    transform-box: fill-box;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://d3js.org/d3.v4.min.js"></script>

<svg id = "barchart" width="600" height="500">    <defs>
        <pattern id="pattern1"
                 x="0" y="0" width="20" height="20"
                 patternUnits="userSpaceOnUse" >
      
<!--             <circle cx="10" cy="10" r="10" style="stroke: none; fill: #0000ff" /> -->
          <rect id="rotateRect" x="5" y = "5" width = "10" height = "10" />
      
        </pattern>
      </defs>
    
      <defs>
        <pattern id="pattern2"
                 x="0" y="0" width="20" height="20"
                 patternUnits="userSpaceOnUse" >
      
            <circle cx="10" cy="10" r="5" style="stroke: none; fill: #0000ff" />
      
        </pattern>
      </defs>
    
      <defs>
        <pattern id="pattern3"
                 x="0" y="0" width="20" height="20"
                 patternUnits="userSpaceOnUse" >
      
            <circle cx="10" cy="10" r="3" style="stroke: none; fill: #0000ff" />
      
        </pattern>
      </defs>
</svg>

<button id="btn">Save SVG</button>
Robert Longson
  • 118,664
  • 26
  • 252
  • 242
  • Thank you for your answer, it clearly solved my question! But what if there are multiple charts (in multiple ``) that need to use the same patterns? I can only put the patterns in one ``, then how can I download other charts filled with patterns? – Tingying He Aug 27 '22 at 20:24
  • 1
    Move the patterns before you export. – Robert Longson Aug 27 '22 at 20:26
  • Thanks a lot! In my actual project, there are `` within the ``. I put the `` in the same `` as the chart. But I found when I download the chart svg, the chart were not filled, all images disappeared. May I ask do you know why? – Tingying He Aug 27 '22 at 21:21