This example shows one way to encapsulate the D3 Margin Convention using Model.js.
Check out the resize behavior in full screen mode.
More generally, this example is an experiment in how to generalize self-contained pieces of dynamic graphical behavior. Note that the following three pieces of this visualization are each implemented in separate functions:
width
and height
top
and left
width
and height
, which represent the dimensions of the rectangle inside the margin.Draws from:
xxxxxxxxxx
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script src="https://curran.github.io/model/cdn/model-v0.2.4.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
#visualization-container { width: 100%; height: 100%; }
</style>
</head>
<body>
<div id="visualization-container"></div>
<script>
function marginConvention(my, svg, g){
my.when("box", function (box){
svg.attr("width", box.width)
.attr("height", box.height);
});
my.when(["box", "margin"], function (box, margin){
my.width = box.width - margin.left - margin.right;
my.height = box.height - margin.top - margin.bottom;
g.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
});
}
function backgroundRect(my, g){
var rect = g.append("rect").style("fill", "#aaaaaa");
my.when(["width", "height"], function (width, height) {
rect.attr("width", width).attr("height", height);
});
}
function Visualization(){
var my = new Model({
margin: {top: 20, right: 10, bottom: 20, left: 10}
});
my.el = document.createElementNS("https://www.w3.org/2000/svg", "svg");
var svg = d3.select(my.el).style("background-color", "lightgray");
var g = svg.append("g");
marginConvention(my, svg, g);
backgroundRect(my, g);
return my;
}
var visualization = new Visualization();
visualization.box = { width: 960, height: 500 };
d3.select("#visualization-container").node()
.appendChild(visualization.el);
console.log("you are now rocking with d3 and model.js", d3, visualization);
</script>
</body>
Modified http://curran.github.io/model/cdn/model-v0.2.4.js to a secure url
https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js
https://curran.github.io/model/cdn/model-v0.2.4.js