Essentially, you need to move the inline styles to the elements. Your g axis path, for example, comes from:
<g class="x axis" transform="translate(0,450)"> <path class="domain" d="M0,6V0H440V6"></path> </g>
To:
<g class="x axis" transform="translate(0,450)"> <path class="domain" d="M0,6V0H440V6" style="fill: none; stroke: #000; stroke-width: 1px; shape-rendering: crispEdges;"> </path> </g>
There is some sort of recursion tricks , but a complete recursion for all the elements probably went a little too far (and will be slow).
I would either manually move the styles in a line, or do something to target the right elements. For example, here is how you can fix the axis:
d3.selectAll('.axis path, .axis line, .axis').each(function() { var element = this; var computedStyle = getComputedStyle(element, null); for (var i = 0; i < computedStyle.length; i++) { var property = computedStyle.item(i); var value = computedStyle.getPropertyValue(property); element.style[property] = value; } });
Full working example:
<!DOCTYPE html> <meta charset="utf-8"> <style> .axis { font: 10px sans-serif; } .axis path, .axis line { fill: none; stroke: #000; shape-rendering: crispEdges; } .x.axis path { display: none; } </style> <body> <button id="save">Save as Image</button> <div id="svgdataurl"></div> <span id="h3"> </span> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script> <script> var margin = { top: 20, right: 20, bottom: 30, left: 40 }, width = 500 - margin.left - margin.right, height = 500 - margin.top - margin.bottom; var x = d3.scale.linear() .range([0, width]); var y = d3.scale.linear() .range([height, 0]); var xAxis = d3.svg.axis() .scale(x) .orient("bottom"); var yAxis = d3.svg.axis() .scale(y) .orient("left"); var svg = d3.select("#h3").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); x.domain([0, 100]); y.domain([0, 100]); svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xAxis); svg.append("g") .attr("class", "y axis") .call(yAxis) .append("text") .attr("transform", "rotate(-90)") .attr("y", 6) .attr("dy", ".71em") .style("text-anchor", "end"); d3.select("#save").on("click", function() { d3.selectAll('.axis path, .axis line, .axis').each(function() { var element = this; var computedStyle = getComputedStyle(element, null); for (var i = 0; i < computedStyle.length; i++) { var property = computedStyle.item(i); var value = computedStyle.getPropertyValue(property); element.style[property] = value; } }); var html = d3.select('#h3 svg') .attr("version", 1.1) .attr("xmlns", "http://www.w3.org/2000/svg") </script>
source share