Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// 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
You can’t perform that action at this time.