轉(zhuǎn)換是動態(tài)操作
轉(zhuǎn)換是從一個start狀態(tài)轉(zhuǎn)換為end的一個動態(tài)過程. 例如我們將頁面的背景色從green轉(zhuǎn)換為red.
d3.select('body')
.style('background-color', 'green')
.transition()
.delay(1000)
.style('background-color', 'red');
我們可以監(jiān)聽transition的start/end事件:
d3.select('body')
.transition()
.delay(1000)
.on('start', function() { d3.select(this).style('background-color', 'green')})
.style('background-color', 'red')
.on('end', () => console.log('end...'));
更簡單的方法在于使用類似styleTween/attrTween的方法(不確定是否常用):
d3.select('body').transition()
.styleTween('background-color', () => d3.interpolate('green', 'red'));
針對d3.interpolate, 它需要知道給予參數(shù)的合理性(例如('green', 'red'), 則顏色從green過渡到red). 目前規(guī)則如下:
- numbers
- colors
- geometric transforms
- strings with embedded numbers(例如"96px")
但如果是自己實(shí)現(xiàn)interplator, 則需要類似下列的寫法: 保證t=0時候返回a, t=1時候返回b:
function interpolateNumber(a, b) {
return function(t) {
return a + t * (b - a);
}
}
轉(zhuǎn)換的生命周期
周期分為四個部分:
- 轉(zhuǎn)換寫入計(jì)劃表
- 轉(zhuǎn)換開始start
- 轉(zhuǎn)換運(yùn)行run
- 轉(zhuǎn)換結(jié)束end
當(dāng)我們寫selection.transition時候, 轉(zhuǎn)換就寫入計(jì)劃表中. 則start在delay后面運(yùn)行; 否則start會盡可能快的運(yùn)行. 當(dāng)執(zhí)行run情況下, 它會重復(fù)調(diào)用t從0~1所返回的值. 當(dāng)t=1的時候, 執(zhí)行end操作.
實(shí)例: 在enter/update/exit中執(zhí)行transition
const width = 960;
const height = 500;
const x = d3.scalePoint()
.domain([0, 1, 2])
.range([height / 4, width - height / 4]);
const svg = d3.select('svg');
let circle = svg.selectAll('circle')
.data([0, 1])
.enter().append('circle')
.attrs({
r: height / 4,
cx: x,
cy: height / 2
});
setTimeout(() => {
circle = circle.data([1, 2], d => d);
circle.transition().duration(750)
.attr('r', height / 3)
.style('fill', 'orange');
circle.enter().append('circle')
.attrs({
r: height / 4,
cx: x,
cy: height / 2
})
.style('fill', 'green');
circle.exit().transition()
.attrs({
r: 1e-6,
fill: 'red'
})
.remove();
}, 1000)
- 使用d3.scalePoint, 將domain和range對應(yīng)起來.
- 預(yù)先繪制[0, 1]兩個黑色的圓圈, 以750毫秒的速度繪制[1, 2]兩個圓圈, 半徑調(diào)整為height / 3, 顏色設(shè)置為橘色.
- 將新增的2號圓圈, 半徑設(shè)置為height / 4, 并且顏色為green.
- 將0號圓圈的半徑設(shè)置為1e-6, 填充紅色, 并刪除.
源碼
https://github.com/leicj/d3/blob/master/src/components/transition.js