Public
Edited
Aug 29, 2023
3 forks
4 stars
Insert cell
Insert cell
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
Insert cell
rectWidth = 30
Insert cell
height = 480
Insert cell
width = 900
Insert cell
Insert cell
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more