Skip to content

Instantly share code, notes, and snippets.

@chule
Last active January 3, 2016 05:49
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 chule/8418552 to your computer and use it in GitHub Desktop.
Save chule/8418552 to your computer and use it in GitHub Desktop.
D3 spiral matrix
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>D3 spiral matrix</title>
<style>
body {
width: 960px;
height: 500px;
background-color: #3E3E40;
color: #ccc;
font-family: "Helvetica Neue", Helvetica, sans-serif;
font-size: 14px;
}
.left {
margin-left: 20px;
margin-top: 150px;
float:left;
width: 140px;
}
</style>
</head>
<body>
<div>
<div class="left">
Number of columns:<br/>
<input id="width" size="8"/><br/>
Number of rows:<br/>
<input id="height" size="8"/><br/>
<button id="button">Create table</button>
</div>
<div class="svg">
</div>
</div>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
var svg = d3.select(".svg").append("svg").attr({
"width": "800",
"height": "500",
});
var placeRectangle = function (data) {
d3.selectAll(".table").remove();
var groups = svg.selectAll("g")
.data(data).enter()
.append("g")
.attr("transform", function (d, i) {
var x = 44 * d[0] + 20;
var y = (44 * d[1]) + 60;
// console.log([x, y]);
return "translate(" + [x, y] + ")";
}).attr("class", "table");
groups.append("rect").attr({
"x": 0,
"y": 0,
"width": 44,
"height": 44,
"rx": 2,
"ry": 2,
"fill": "none",
"stroke": "#000"
}).transition()
.attr("stroke", "#ffffff")
.duration(500)
.delay(function (d, i) {
return i * 100;
});
groups.append("text").text(function (d, i) {
return i + 1;
}).attr("transform", "translate(17,25)")
.attr("opacity", 0)
.transition()
.attr("opacity", 1)
.duration(500)
.delay(function (d, i) {
return i * 100;
});
};
var calculatePositions = function (width, height) {
var myArray = [];
var generateBottomLeft = function (x1, y1, x2, y2) {
for (i = x2; i >= x1; i -= 1) {
myArray.push([i, y2]);
}
for (j = y2 - 1; j >= y1; j -= 1) {
myArray.push([x1, j]);
}
if ((x2 - x1) && (y2 - y1) > 0) {
generateTopRight(x1 + 1, y1, x2, y2 - 1);
}
};
var generateTopRight = function (x1, y1, x2, y2) {
for (i = x1; i <= x2; i += 1) {
myArray.push([i, y1]);
}
for (j = y1 + 1; j <= y2; j += 1) {
myArray.push([x2, j]);
}
if ((x2 - x1) && (y2 - y1) > 0) {
generateBottomLeft(x1, y1 + 1, x2 - 1, y2);
}
};
generateBottomLeft(1, 1, width, height);
placeRectangle(myArray);
};
var button = d3.select("#button");
button.on("click", function () {
var x = document.getElementById("width").value;
var y = document.getElementById("height").value;
calculatePositions(x, y);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment