Published
Edited
Feb 25, 2022
1 star
Insert cell
Insert cell
Insert cell
chart = {

const zoom = d3.zoom()
.scaleExtent([1, 40])
.on("zoom", zoomed);


const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height])
.on("click", reset);

const g = svg.append("g");


g.selectAll("circle")
.data(data)
.join("circle")
.attr("cx", ([x]) => x)
.attr("cy", ([, y]) => y)
.attr("r", radius)
.attr("fill", (d, i) => d3.interpolateRainbow(i / 360))
.on("click", clicked);

svg.call(zoom);

function random() {
const [x, y] = data[Math.floor(Math.random() * data.length)];
svg.transition().duration(2500).call(
zoom.transform,
d3.zoomIdentity.translate(width / 2, height / 2).scale(40).translate(-x, -y)
);
}

// 点击空白地方恢复画布
function reset() {
svg.transition().duration(750).call(
zoom.transform, // 使用 zoom.transform 执行平移缩放操作,是绝对变换
d3.zoomIdentity, // d3.zoomIdentity 表示标准缩放变换对象,它的缩放比例与平移值分别为:k=1、tx=ty=0
d3.zoomTransform(svg.node()).invert([width / 2, height / 2]) // 顺滑平移的参考点是视图中心
);
}

// 点击圆形时进行放大并移动到视图中间
function clicked(event, [x, y]) {
event.stopPropagation();
svg.transition().duration(750).call(
zoom.transform,
// 基于 d3.zoomIdentity 构建缩放变换对象
// translate(width / 2, height / 2) 先将视图平移 width/2 和 height/2 为后续的移动「校正」坐标
// 再将画布放大 40 倍
// translate(-x, -y) 最后根据被点击的圆点坐标,将画布反向移动,由于之前做了「校正」,所以最后的效果是被点击的圆点会出现在视图中间
d3.zoomIdentity.translate(width / 2, height / 2).scale(40).translate(-x, -y),
d3.pointer(event) // 顺滑平移的参考点是鼠标点击的位置
);
}

function zoomed({transform}) {
g.attr("transform", transform);
}

return Object.assign(svg.node(), {
zoomIn: () => svg.transition().call(zoom.scaleBy, 2),
zoomOut: () => svg.transition().call(zoom.scaleBy, 0.5),
zoomRandom: random,
zoomReset: reset
});
}
Insert cell
height = 500
Insert cell
radius = 6
Insert cell
step = radius * 2
Insert cell
// 生成 2000 个圆点的圆心定位坐标
// 坐标以视图中心为原点
data = Array.from({length: 2000}, (_, i) => {
const radius = step * Math.sqrt(i += 0.5), a = theta * i;
return [
width / 2 + radius * Math.cos(a),
height / 2 + radius * Math.sin(a)
];
})
Insert cell
theta = Math.PI * (3 - Math.sqrt(5))
Insert cell
d3 = require("d3@6")
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