d3.grid.js
development area
by Nivaldo
HTML
<script src="http://d3js.org/d3.v3.min.js"></script>
<!--
- do a slider for changing magnitude of grid spacing
- offer this feature as background for many kinds of graphs, when it makes sense (challenge will be to keep it on the background because of z-depth problems)
- make this into a bl.ocks.org (could make this into a little plugin)
-->
CSS
svg {
background-color: salmon;
}
text {
font: normal 12px cursive;
stroke-width: 0.50;
stroke: #aaa;
}
/* css styling for grid follows */
/*
.gr-g {
background-color: linen;
}
*/
.gr-bg {
fill: linen; /* NOTE: the one in the lib is set to none */
}
.gr-hline, .gr-vline {
stroke: #ccc;
stroke-width: 1px;
shape-rendering: crispEdges;
}
.gr-axis path, .gr-axis line {
fill: none;
stroke: none;
}
JavaScript
function drawGrid(container,spacing,reversed) {
function findElemProp(elem,prop) {
return (elem[prop] !== 0) ? elem[prop] : findElemProp(elem.parentNode,prop);
}
var width = findElemProp(container.node(),"offsetWidth");
var height = findElemProp(container.node(),"offsetHeight");
var x = d3.scale.linear().domain([0,width]).range([0,width]);
var y = d3.scale.linear().domain([0,height]).range(reversed ? [0,height] : [height,0]);
var tickValues = [];
for(var i = spacing; i<width; i+=spacing) tickValues.push(i);
var xAxis = d3.svg.axis().scale(x).tickValues(tickValues).orient("top");
var yAxis = d3.svg.axis().scale(y).tickValues(tickValues).orient("right");
var g = container.append("g")
.attr("class","gr-g");
g.append("rect")
.attr("class","gr-bg")
.attr("x",0)
.attr("y",0)
.attr("height",height)
.attr("width",width);
// horizontal lines
g.selectAll(".gr-hline")
.data(d3.range(height/spacing + spacing))
.enter()
.append("line")
.attr("class","gr-hline")
.attr("y1", function (d) {return d * spacing;})
.attr("y2", function (d) {return d * spacing;})
.attr("x1", function (d) {return 0;})
.attr("x2", function (d) {return width;})
.attr("transform", "translate(0,0)");
//vertical lines
g.selectAll(".gr-vline")
.data(d3.range(width/spacing + spacing))
.enter()
.append("line")
.attr("class","gr-vline")
.attr("x1", function (d) {return d * spacing;})
.attr("x2", function (d) {return d * spacing;})
.attr("y1", function (d) {return 0;})
.attr("y2", function (d) {return height;})
.attr("transform", "translate(0,0)");
g.append("g")
.attr("class", "gr-x gr-axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.selectAll("text")
...