Skip to content

Instantly share code, notes, and snippets.

@curran
Last active November 20, 2015 01:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save curran/2c736a99c2f57bfac7e4 to your computer and use it in GitHub Desktop.
Save curran/2c736a99c2f57bfac7e4 to your computer and use it in GitHub Desktop.
Margin Convention with Model.js

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:

  • The margin convention, which
    • resizes the SVG element by setting width and height
    • translates the G element by the margin top and left
    • assigns values to the model properties width and height, which represent the dimensions of the rectangle inside the margin.
  • The background X.
  • The clip rectangle, which will clip the corners of the background X to be within the rectangle inside the margin.

Draws from:

<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script src="http://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("http://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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment