Interpolators
interpolate 英文 :插入

数值插值器

  1. // 取值范围 0~1
  2. var interpolate = d3.interpolateNumber(0, 100);
  3. interpolate(0.1); // 10
  4. interpolate(0.99); // 99
  5. // 相当于
  6. function interpolate(t) {
  7. return a * (1 - t) + b * t;
  8. }

字符串插值器

  1. // 当range传入字符串时,会自动使用字符串插值器,会查找字符串中的数字,然后使用d3数字插值器进行插值
  2. var autoStrInter = d3.scaleLinear()
  3. .domain([0, 10])
  4. .range([
  5. "italic bold 12px/30px Georgia, serif",
  6. "italic bold 120px/300px Georgia, serif"
  7. ]);
  8. console.log(autoStrInter(0)); // italic bold 12px/30px Georgia, serif
  9. console.log(autoStrInter(5)); // italic bold 66px/165px Georgia, serif
  10. console.log(autoStrInter(10)); // italic bold 120px/300px Georgia, serif

颜色插值器

  1. var color = d3.scaleLinear()
  2. .domain([0, 5, 10])
  3. .range([
  4. "red",
  5. "blue",
  6. "#fff"
  7. ]);
  8. color(0); // rgb(255, 0, 0)
  9. color(4); // rgb(51, 0, 204)

复合对象插值器 Object

  1. const objFn = d3.scalePow().exponent(2).domain([0, 10]).range([
  2. {color: 'red', height: '15px'},
  3. {color: 'blue', height: '150px'},
  4. ]);
  5. console.log(objFn(0)); // {color: "rgb(255, 0, 0)", height: "15px"}
  6. console.log(objFn(4)); // {color: "rgb(214, 0, 41)", height: "36.6px"}

自定义插值器

  1. const fn = d3.scaleLinear()
  2. .domain([0, 10]).range(["$0", "$300"]).interpolate(function(a, b) {
  3. console.log('a', a); // a $0
  4. console.log('b', b); // b $300
  5. var re = /^\$([0-9,.]+)$/;
  6. var ma;
  7. var mb;
  8. var f = d3.format(",.02f");
  9. if ((ma = re.exec(a)) && (mb = re.exec(b))) {
  10. a = parseFloat(ma[1]);
  11. b = parseFloat(mb[1]) - a;
  12. return function (t) {
  13. console.log(a, b, t); // 0, 300, 0.5
  14. return "$" + f(a + b * t);
  15. }
  16. }
  17. });
  18. console.log(fn(5)); // "$150.00"
  19. const fnInterpolate = d3.scaleLinear()
  20. .domain([0, 27]).range(["a", "z"]).interpolate(function(a, b) {
  21. var re = /^[a-z]$/;
  22. var ma;
  23. var mb;
  24. if ((ma = re.exec(a)) && (mb = re.exec(b))) {
  25. a = a.charCodeAt(0); // 返回ascii
  26. var delta = a - b.charCodeAt(0);
  27. return function (t) {
  28. console.log(a, delta, t); // 97 -25 0.18518518518518517
  29. return String.fromCharCode(Math.ceil(a - delta * t)); // 传入102
  30. }
  31. }
  32. });
  33. console.log(fnInterpolate(5)); // "f"