Published
Edited
Oct 4, 2020
1 star
Insert cell
Insert cell
Insert cell
Insert cell
chart = {
const svg = d3.create('svg')
.attr('width', width)
.attr('height', height)
const rects = d3.range( Math.ceil(height/rectWidth) * Math.ceil(width/rectWidth) )
svg.selectAll('rect')
.data( rects )
.join('rect')
.attr('class', d => 'rect-' + d)
.attr('width', rectWidth)
.attr('height', rectWidth)
.attr('x', (d,i) => rectWidth * (i % (width/rectWidth)))
.attr('y', (d,i) => Math.floor( i/(width/rectWidth) ) * rectWidth)
.style('stroke', 'white')
.style('cursor', 'pointer')
.style('fill', (d,i) => {
const x = rectWidth * (i % (width/rectWidth)),
y = Math.floor( i/(width/rectWidth) ) * rectWidth,
dist = Math.hypot( x, y )
return d3.interpolateSpectral( dist / Math.hypot( width, height ) )
})
// The code for moving a single rect out of place is at the bottom of the lesson
return svg.node()

}
Insert cell
Insert cell
drag = {

function dragStart(d) {
d3.select( this )
.raise()
.style('stroke', 'black')
}
function dragging(d) {
d3.select( this )
.attr('x', d3.event.x - rectWidth/2)
.attr('y', d3.event.y - rectWidth/2)
// If you uncomment below, the color of the rect will change as you drag :D
// .style('fill', () => {
// return d3.interpolateSpectral( Math.hypot(d3.event.x, d3.event.y) / Math.hypot( width, height ) )
// })
}
function dragEnd(d) {
d3.select( this ).style('stroke', 'white')
}

return d3.drag()
.on('start', dragStart)
.on('drag', dragging)
.on('end', dragEnd)
}
Insert cell
Insert cell
d3.select( chart )
.selectAll('rect')
.call( drag )
Insert cell
Insert cell
// Code for randomly choosing a rect and moving it out of place :)
{
const randomRectNumber = Math.floor(Math.random() * Math.ceil(height/rectWidth) * Math.ceil(width/rectWidth))
d3.select(chart)
.select('.rect-' + randomRectNumber)
.raise()
.attr('x', Math.random() * (width - 30))
.attr('y', Math.random() * (height - 30))
.style('stroke', 'black')

}
Insert cell
Insert cell
rectWidth = 30
Insert cell
height = 480
Insert cell
width = 900
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more