Built with blockbuilder.org
forked from noblemillie's block: dynamic grid w/ assorted styling
forked from noblemillie's block: dynamic grid
xxxxxxxxxx
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body {
margin:0;
position:fixed;
top:0;
right:0;
bottom:0;
left:0;
padding: 20px;
}
.axis .grid-line{
stroke: black;
shape-rendering: crispEdges;
stroke-opacity: .2;
}
</style>
</head>
<body>
<div class="control-group">
<button onclick="rescale()">rescale grid</button>
</div>
<script type="text/javascript">
var height = 400,
width = 400,
margin = 25,
xAxis, yAxis, xAxisLength, yAxisLength;
var svg = d3.select("body").append("svg")
.attr("class", "axis")
.attr("width", width)
.attr("height", height);
function renderXAxis(){
xAxisLength = width - 2 * margin;
var scale = d3.scaleLinear()
.domain([0, 100])
.range([0, xAxisLength]);
xAxis = d3.axisBottom()
.scale(scale)
.ticks(10)
.tickSize(12) // <-A
.tickPadding(3);
svg.append("g")
.attr("class", "x-axis")
.attr("transform", function(){
return "translate(" + margin + "," + (height - margin) + ")";
})
.call(xAxis);
}
function renderYAxis(){
yAxisLength = height - 2 * margin;
var scale = d3.scaleLinear()
.domain([100, 0])
.range([0, yAxisLength]);
yAxis = d3.axisLeft()
.scale(scale)
.ticks(4)
.tickSize(2) // <-A
.tickPadding(2)
.tickFormat(d3.format("$"));
;
svg.append("g")
.attr("class", "y-axis")
.attr("transform", function(){
return "translate(" + margin + "," + margin + ")";
})
.call(yAxis);
}
function rescale(){
var max = Math.round(Math.random() * 100);
xAxis.scale().domain([0, max]);
svg.select("g.x-axis")
.transition()
.call(xAxis);
yAxis.scale().domain([max, 0]);
svg.select("g.y-axis")
.transition()
.call(yAxis);
renderXGridlines();
renderYGridlines();
}
function renderXGridlines(){
d3.selectAll("g.x-axis g.tick")
.select("line.grid-line")
.remove();
d3.selectAll("g.x-axis g.tick")
.append("line")
.classed("grid-line", true)
.attr("x1", 0)
.attr("y1", 0)
.attr("x2", 0)
.attr("y2", - yAxisLength);
}
function renderYGridlines(){
d3.selectAll("g.y-axis g.tick")
.select("line.grid-line").remove();
d3.selectAll("g.y-axis g.tick")
.append("line")
.classed("grid-line", true)
.attr("x1", 0)
.attr("y1", 0)
.attr("x2", xAxisLength)
.attr("y2", 0);
}
renderYAxis();
renderXAxis();
renderXGridlines();
renderYGridlines();
</script>
</body>
https://d3js.org/d3.v4.min.js