Skip to content

d3-interpolate

此模块提供了多种用于混合两个值的插值方法。值可以是数字、颜色、字符串、数组,甚至是深度嵌套的对象。例如:

¥This module provides a variety of interpolation methods for blending between two values. Values may be numbers, colors, strings, arrays, or even deeply-nested objects. For example:

js
const i = d3.interpolateNumber(10, 20);
i(0.0); // 10
i(0.2); // 12
i(0.5); // 15
i(1.0); // 20

返回的函数 i 是一个插值器。给定起始值 a 和终止值 b,它接受一个参数 t,该参数通常在 [0, 1] 范围内,并返回相应的插值值。插值器通常在 t = 0 时返回一个相当于 a 的值,在 t = 1 时返回一个相当于 b 的值。

¥The returned function i is an interpolator. Given a starting value a and an ending value b, it takes a parameter t typically in [0, 1] and returns the corresponding interpolated value. An interpolator typically returns a value equivalent to a at t = 0 and a value equivalent to b at t = 1.

你可以插入除数字之外的更多内容。要找到钢蓝色和棕色之间的感知中点:

¥You can interpolate more than just numbers. To find the perceptual midpoint between steelblue and brown:

js
d3.interpolateLab("steelblue", "brown")(0.5); // "rgb(142, 92, 109)"

或者,使用从 t = 0 到 t = 1 的颜色渐变:

¥Or, as a color ramp from t = 0 to t = 1:

以下是一个更详细的例子,演示了 interpolate 使用的类型推断:

¥Here’s a more elaborate example demonstrating type inference used by interpolate:

js
const i = d3.interpolate({colors: ["red", "blue"]}, {colors: ["white", "black"]});
i(0.0); // {colors: ["rgb(255, 0, 0)", "rgb(0, 0, 255)"]}
i(0.5); // {colors: ["rgb(255, 128, 128)", "rgb(0, 0, 128)"]}
i(1.0); // {colors: ["rgb(255, 255, 255)", "rgb(0, 0, 0)"]}

请注意,通用值插值器不仅可以检测嵌套对象和数组,还可以检测颜色字符串和嵌入在字符串中的数字!

¥Note that the generic value interpolator detects not only nested objects and arrays, but also color strings and numbers embedded in strings!

请参阅以下之一:

¥See one of: