Skip to content

Instantly share code, notes, and snippets.

@eesur
Created November 24, 2015 19:02
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 eesur/b6f66a98e398c0df28e6 to your computer and use it in GitHub Desktop.
Save eesur/b6f66a98e398c0df28e6 to your computer and use it in GitHub Desktop.
d3 | squared grid coloured in

Coloured in the grid, so it differs from your average squared paper–can't do that by hand every second

based of my initial sketch/block: d3 | simple square grid

var square = 20,
w = 900,
h = 600;
var tcColours = ['#FDBB30', '#130C0E', '#EC008C', '#EE3124', '#F47521', '#7AC143', '#00B0DD'];
// create the svg
var svg = d3.select('#grid').append('svg')
.attr({
width: w,
height: h
});
// calculate number of rows and columns
var squaresRow = _.round(w / square);
var squaresColumn = _.round(h / square);
// loop over number of columns
_.times(squaresColumn, function(n) {
// create each set of rows
var rows = svg.selectAll('rect' + ' .row-' + (n + 1))
.data(d3.range(squaresRow))
.enter().append('rect')
.attr({
class: function(d, i) {
return 'square row-' + (n + 1) + ' ' + 'col-' + (i + 1);
},
id: function(d, i) {
return 's-' + (n + 1) + (i + 1);
},
width: square,
height: square,
x: function(d, i) {
return i * square;
},
y: n * square,
fill: tcColours[_.random(0, tcColours.length)],
stroke: 'none'
});
});
// use each to change the squares randomly
function setColours() {
d3.select(this).attr('fill', tcColours[_.random(0, tcColours.length)] );
}
d3.selectAll('.square').each(setColours);
// repeat till dizzy
setInterval(function (){
d3.selectAll('.square').each(setColours);
}, 1000);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>d3 | simple square grid with colours</title>
<meta name="author" content="Sundar Singh | eesur.com">
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.min.js" charset="utf-8"></script>
<style type="text/css">
body{
background-color: #130C0E;
width: 960px;
margin: 20px auto;
}
</style>
</head>
<section id='grid'></section>
<script src="d3_code_grid_colours.js" charset="utf-8"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment