Published
Edited
Apr 8, 2021
2 stars
Insert cell
md`# Slider with thumbnail`
Insert cell
d3 = require("d3@6")
Insert cell
margin = ({top: 10, right: 120, bottom: 10, left: 40})
Insert cell
chart = {
let config_size = {
'svg_height': 100,
'svg_width': 500,
'img_height': 75,
'img_padding': 5,
'slider_height': 20,
}
config_size.slider_y = config_size.svg_height - config_size.slider_height;
config_size.img_offset = config_size.img_height + config_size.img_padding;
const svg = d3.create("svg").attr("width", config_size.svg_width).attr("height", config_size.svg_height);
const vals = d3.range(20);

const group = svg.append('g').classed('big-group', true);

const big_size = config_size.img_height;
const big_rect = group.selectAll('rect.big').data(vals).join('rect').classed('big', true)
.attr('fill', (d,i) => d3.interpolateRainbow(i / vals.length))
.attr('x', (d,i) => config_size.img_offset * i)
.attr('y', 0)
.attr('width', config_size.img_height).attr('height', config_size.img_height);
const small_size = Math.min(config_size.svg_width / vals.length, config_size.slider_height);
const small_rect = svg.selectAll('rect.small').data(vals).join('rect').classed('small', true)
.attr('fill', (d,i) => d3.interpolateRainbow(i / vals.length))
.attr('x', (d,i) => config_size.svg_width / (2 * vals.length) * (2 * i + 1) - small_size / 2)
.attr('y', config_size.slider_y + config_size.slider_height/2 - small_size / 2)
.attr('width', small_size).attr('height', small_size);

const big2small_ratio = config_size.svg_width / (vals.length) / config_size.img_offset
const slider_width = config_size.svg_width * big2small_ratio;

let deltaX = 0;
const slider = svg.append('rect').classed('slider', true)
.attr('width', slider_width).attr('height', config_size.slider_height)
.attr('x', 0).attr('y', config_size.slider_y)
.attr('fill', 'gray')
.attr('fill-opacity', 0.3)
.attr('stroke', 'gray')
.attr('stroke-opacity', 0.7)
.call(d3.drag()
.on("start", function(event, d) {
deltaX = d3.select(this).attr("x") - event.x;
})
.on("drag", function(event, d) {
if (event.x + deltaX < 0 || event.x + deltaX + slider_width > config_size.svg_width) return;
d3.select(this).attr("x", event.x + deltaX);
group.attr('transform', `translate(${-(event.x + deltaX)/big2small_ratio},${0})`)
}));
return svg.node();
}
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