Interpolators
interpolate 英文 :插入
数值插值器
// 取值范围 0~1
var interpolate = d3.interpolateNumber(0, 100);
interpolate(0.1); // 10
interpolate(0.99); // 99
// 相当于
function interpolate(t) {
return a * (1 - t) + b * t;
}
字符串插值器
// 当range传入字符串时,会自动使用字符串插值器,会查找字符串中的数字,然后使用d3数字插值器进行插值
var autoStrInter = d3.scaleLinear()
.domain([0, 10])
.range([
"italic bold 12px/30px Georgia, serif",
"italic bold 120px/300px Georgia, serif"
]);
console.log(autoStrInter(0)); // italic bold 12px/30px Georgia, serif
console.log(autoStrInter(5)); // italic bold 66px/165px Georgia, serif
console.log(autoStrInter(10)); // italic bold 120px/300px Georgia, serif
颜色插值器
var color = d3.scaleLinear()
.domain([0, 5, 10])
.range([
"red",
"blue",
"#fff"
]);
color(0); // rgb(255, 0, 0)
color(4); // rgb(51, 0, 204)
复合对象插值器 Object
const objFn = d3.scalePow().exponent(2).domain([0, 10]).range([
{color: 'red', height: '15px'},
{color: 'blue', height: '150px'},
]);
console.log(objFn(0)); // {color: "rgb(255, 0, 0)", height: "15px"}
console.log(objFn(4)); // {color: "rgb(214, 0, 41)", height: "36.6px"}
自定义插值器
const fn = d3.scaleLinear()
.domain([0, 10]).range(["$0", "$300"]).interpolate(function(a, b) {
console.log('a', a); // a $0
console.log('b', b); // b $300
var re = /^\$([0-9,.]+)$/;
var ma;
var mb;
var f = d3.format(",.02f");
if ((ma = re.exec(a)) && (mb = re.exec(b))) {
a = parseFloat(ma[1]);
b = parseFloat(mb[1]) - a;
return function (t) {
console.log(a, b, t); // 0, 300, 0.5
return "$" + f(a + b * t);
}
}
});
console.log(fn(5)); // "$150.00"
const fnInterpolate = d3.scaleLinear()
.domain([0, 27]).range(["a", "z"]).interpolate(function(a, b) {
var re = /^[a-z]$/;
var ma;
var mb;
if ((ma = re.exec(a)) && (mb = re.exec(b))) {
a = a.charCodeAt(0); // 返回ascii
var delta = a - b.charCodeAt(0);
return function (t) {
console.log(a, delta, t); // 97 -25 0.18518518518518517
return String.fromCharCode(Math.ceil(a - delta * t)); // 传入102
}
}
});
console.log(fnInterpolate(5)); // "f"