1 回答

TA貢獻(xiàn)1886條經(jīng)驗(yàn) 獲得超2個(gè)贊
將畫(huà)筆視為數(shù)據(jù),因?yàn)樗鼈冇成涞?x 軸上的每個(gè)序數(shù)值。使用 .enter 創(chuàng)建畫(huà)筆并附加所有必要的功能。.each 函數(shù)類似于調(diào)用,但分別在每個(gè)元素上運(yùn)行。這對(duì)于包含畫(huà)筆的生成非常有用。
xData = ["A", "B", "C", "D"];
var margin = {
top: 20,
right: 20,
bottom: 30,
left: 50
},
width = 960 - margin.left - margin.right,
height = 180 - margin.top - margin.bottom;
var x = d3.scale.ordinal()
.domain(xData)
.rangeBands([0, 200])
var y = d3.scale.linear()
.range([height, 0])
.domain([0, 100])
var xAxis = d3.svg.axis()
.scale(x)
var svg = d3.select("#timeline").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
const brushes = svg.selectAll('g.brush')
.data(xData)
.enter()
.append('g')
.attr('class', 'brush')
.each(function(d) {
const el = d3.select(this);
const brush = d3.svg.brush().y(y).on("brushend", () => console.log(d, ' Extent: ', brush.extent()));
el.call(brush);
el.selectAll("rect")
.attr("x", x(d))
.attr("width", 20);
});
.brush {
fill: lightgray;
fill-opacity: .75;
shape-rendering: crispEdges;
}
<script src='https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.6/d3.min.js'></script>
<div class="container">
<div id="timeline"></div>
</div>
添加回答
舉報(bào)