Reputation: 167
I am trying to create a responsive SVG. I have successfully created an example SVG:
<html xmlns:xlink="http://www.w3.org/1999/xlink"><head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
</head>
<body>
<div id="container">
<svg viewBox="0 0 600 200" preserveAspectRatio="xMidYMid" id="chart">
<circle fill="red" cy="100" cx="100" r="100"></circle>
<circle fill="blue" cy="100" cx="300" r="100"></circle>
<circle fill="green" cy="100" cx="500" r="100"></circle>
</svg>
</div>
</body></html>
https://jsfiddle.net/andrewsu/kombdqL2/4/
https://gist.github.com/andrewsu/d3ed340495a2f21a25f8f69dedb2096a
If you adjust the panel boundaries in the jsfiddle version, you can see the circles scaling in size appropriately.
I'd like to create the exact same SVG using D3.
<html xmlns:xlink="http://www.w3.org/1999/xlink"><head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<script type="text/javascript" src="http://d3js.org/d3.v3.js"></script>
</head>
<body>
<div id="container">
</div>
<script type="text/javascript">
var width=600, height=200;
var svg = d3.select("#container").append("svg")
.attr("id","chart")
.attr("preserveAspectRatio", "xMidYMid")
.attr("viewbox", "0 0 "+ width + " " + height);
svg.append("circle")
.attr("r","100")
.attr("cx","100")
.attr("cy","100")
.attr("fill","red");
svg.append("circle")
.attr("r","100")
.attr("cx","300")
.attr("cy","100")
.attr("fill","blue");
svg.append("circle")
.attr("r","100")
.attr("cx","500")
.attr("cy","100")
.attr("fill","green");
</script>
</body></html>
https://jsfiddle.net/andrewsu/g1x3s2ny/5/
https://gist.github.com/andrewsu/bf0e7549934f93ac40a416dc17bb7b1e
As near as I can tell, the rendered HTML is exactly the same, but the second example does not work correctly (see the jsfiddle).
Oddly to me, if I use my browser's inspector to change any of the four numbers in the viewBox attribute, the behavior immediately works as expected.
Thoughts?
Upvotes: 4
Views: 126
Reputation: 102218
viewBox
has an uppercase B:
.attr("viewBox", "0 0 "+ width + " " + height);
Check your fiddle now: https://jsfiddle.net/on17ga9u/
Here is the documentation: https://www.w3.org/TR/SVG/coords.html#ViewBoxAttribute
Upvotes: 3