我正在努力使这个基本的D3图表响应。我添加了一个事件监听器,它调用resize函数,我在其中更新x和y比例并更改了svg的宽度和高度,并使用更新的值调用init函数。谢谢!
let w = () => {return window.innerWidth}
let h = () => {return window.innerHeight}
let svg = d3.select("body")
.append("svg")
.attr("width", w())
.attr("height", h())
let data = d3.range(25).map(function() {
return parseInt(Math.random() * 100)
})
const margin = () => {return {right: parseInt(w()*.95),
bottom: parseInt(h()*.95)}
}
let x = d3.scaleLinear()
.domain([0, d3.max(data)])
.range([0, margin().right])
let y = d3.scaleLinear()
.domain([0, data.length])
.range([0, margin().bottom])
const init = () => {
svg.selectAll(".bar")
.data(data)
.enter()
.append("rect")
.classed("bar", true)
.attr("x", 0)
.attr("y", (d, i) => y(i))
.attr("width", (d) => {return x(d)})
.attr("height", (d) => {return y(1) - 1})
.attr("fill", (d) => {return "rgb(0, 0, " + d + ")"})
.on("mouseover", function() {
d3.select(this).attr("fill", "red")
})
.on("mouseout", function(d) {
d3.select(this).attr("fill", "rgb(0, 0, " + d + ")")
})
svg.selectAll(".bar-label")
.data(data)
.enter()
.append("text")
.classed("bar-label", true)
.attr("x", (d) => {return x(d)})
.attr("dx",(d) => {return x(1)})
.attr("y", (d,i) => {return y(i)})
.attr("dy", (d,i) => {return y(1) / 1.5})
.text((d) => {return d})
}
const resize = () => {
svg.attr("width", w())
.attr("height", h())
x = d3.scaleLinear()
.domain([0, d3.max(data)])
.range([0, margin().right])
y = d3.scaleLinear()
.domain([0, data.length])
.range([0, margin().bottom])
init()
}
init()
d3.select(window).on("resize", resize)
</script>
</html>