Skip to content

Instantly share code, notes, and snippets.

@mathisonian
Last active January 27, 2016 05:08
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 mathisonian/45c95fdfa41923c7bda7 to your computer and use it in GitHub Desktop.
Save mathisonian/45c95fdfa41923c7bda7 to your computer and use it in GitHub Desktop.
// Assume a variable called `svg`
// has already been created,
// corresponding to a d3 selection
// of an SVG element.
//
// For this example take the
// 'size' of the svg to be 202x202 pixels
var marginSize = 1;
var squareSize = 20;
var numSquares = 10;
// totalSize === 202px === numSquares * squareSize + 2 * margin
var data = d3.range(numSquares).map(function (d, i) {
return i;
});
// draw a rect to act as an outline
svg.append('rect')
.style('fill', '#888')
.attr('width', numSquares * squareSize + 2 * margin)
.attr('height', numSquares * squareSize + 2 * margin);
// Draw the checkerboard pattern.
// This creates 10 groups,
// each with 10 rectanges.
svg.selectAll('g')
.data(data)
.enter()
.append('g')
.selectAll('rect')
.data(data)
.enter()
.append('rect')
.attr('x', function(d) {
// offset by 1 to account for outline
return d * squareSize + marginSize;
})
.attr('y', function() {
var i = d3.select(this.parentNode).datum();
// offset by 1 to account for outline
return i * squareSize + marginSize;
})
.attr('width', squareSize)
.attr('height', squareSize)
.style('fill', function(d) {
var i = d3.select(this.parentNode).datum();
if ((i + d) % 2 !== 0) {
return 'black';
}
return 'white';
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment