Security News
GitHub Removes Malicious Pull Requests Targeting Open Source Repositories
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
d3-interpolate
Advanced tools
The d3-interpolate package provides a variety of interpolation methods for smooth transitions between values in data visualization and animation. It is part of the D3 (Data-Driven Documents) suite of tools, which are used for manipulating documents based on data. d3-interpolate can interpolate numbers, colors, strings, arrays, objects, and even transform strings for complex animations.
Number Interpolation
Interpolates between two numbers. Given a starting number and an ending number, it creates a function that takes a parameter 't' between 0 and 1 and returns the interpolated value.
const interpolate = d3.interpolateNumber(0, 10);
console.log(interpolate(0.5)); // 5
Color Interpolation
Interpolates between two colors. It creates a function that takes a parameter 't' and returns the color that is 't' of the way from the start color to the end color.
const interpolate = d3.interpolateRgb('blue', 'red');
console.log(interpolate(0.5)); // rgb(128, 0, 128)
Object Interpolation
Interpolates between two objects. It interpolates each property of the object that can be interpolated and returns a new object with the interpolated values.
const interpolate = d3.interpolateObject({x: 0}, {x: 10});
console.log(interpolate(0.5)); // {x: 5}
Array Interpolation
Interpolates between two arrays. It interpolates each element of the array and returns a new array with the interpolated values.
const interpolate = d3.interpolateArray([0, 1], [10, 20]);
console.log(interpolate(0.5)); // [5, 10.5]
String Interpolation
Interpolates between two strings that represent transform operations. It is useful for smoothly transitioning SVG elements through transform changes.
const interpolate = d3.interpolateString('rotate(0)', 'rotate(90)');
console.log(interpolate(0.5)); // rotate(45)
A small library for linear interpolation of numbers. It is more focused and lightweight compared to d3-interpolate, which offers a broader range of interpolation options.
A library for all kinds of color conversions and color scales. While it includes color interpolation, it is more comprehensive in terms of color manipulation compared to d3-interpolate.
A powerful animation library that includes interpolation among its features. It is more focused on complex animations and has a broader scope than 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:
const i = d3.interpolateNumber(10, 20);
i(0.0); // 10
i(0.2); // 12
i(0.5); // 15
i(1.0); // 20
The returned function i
is called an interpolator. Given a starting value a and an ending value b, it takes a parameter t in the domain [0, 1] and returns the corresponding interpolated value between a and b. 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:
d3.interpolateLab("steelblue", "brown")(0.5); // "rgb(142, 92, 109)"
Here’s a more elaborate example demonstrating type inference used by interpolate:
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!
If you use npm, npm install d3-interpolate
. You can also download the latest release on GitHub. For vanilla HTML in modern browsers, import d3-interpolate from Skypack:
<script type="module">
import {interpolateRgb} from "https://cdn.skypack.dev/d3-interpolate@3";
const interpolate = interpolateRgb("steelblue", "brown");
</script>
For legacy environments, you can load d3-interpolate’s UMD bundle from an npm-based CDN such as jsDelivr; a d3
global is exported. (If using color interpolation, also load d3-color.)
<script src="https://cdn.jsdelivr.net/npm/d3-color@3"></script>
<script src="https://cdn.jsdelivr.net/npm/d3-interpolate@3"></script>
<script>
const interpolate = d3.interpolateRgb("steelblue", "brown");
</script>
# d3.interpolate(a, b) · Source, Examples
Returns an interpolator between the two arbitrary values a and b. The interpolator implementation is based on the type of the end value b, using the following algorithm:
Based on the chosen interpolator, a is coerced to the suitable corresponding type.
# d3.interpolateNumber(a, b) · Source, Examples
Returns an interpolator between the two numbers a and b. The returned interpolator is equivalent to:
function interpolator(t) {
return a * (1 - t) + b * t;
}
Caution: avoid interpolating to or from the number zero when the interpolator is used to generate a string. When very small values are stringified, they may be converted to scientific notation, which is an invalid attribute or style property value in older browsers. For example, the number 0.0000001
is converted to the string "1e-7"
. This is particularly noticeable with interpolating opacity. To avoid scientific notation, start or end the transition at 1e-6: the smallest value that is not stringified in scientific notation.
# d3.interpolateRound(a, b) · Source, Examples
Returns an interpolator between the two numbers a and b; the interpolator is similar to interpolateNumber, except it will round the resulting value to the nearest integer.
# d3.interpolateString(a, b) · Source, Examples
Returns an interpolator between the two strings a and b. The string interpolator finds numbers embedded in a and b, where each number is of the form understood by JavaScript. A few examples of numbers that will be detected within a string: -1
, 42
, 3.14159
, and 6.0221413e+23
.
For each number embedded in b, the interpolator will attempt to find a corresponding number in a. If a corresponding number is found, a numeric interpolator is created using interpolateNumber. The remaining parts of the string b are used as a template: the static parts of the string b remain constant for the interpolation, with the interpolated numeric values embedded in the template.
For example, if a is "300 12px sans-serif"
, and b is "500 36px Comic-Sans"
, two embedded numbers are found. The remaining static parts (of string b) are a space between the two numbers (" "
), and the suffix ("px Comic-Sans"
). The result of the interpolator at t = 0.5 is "400 24px Comic-Sans"
.
# d3.interpolateDate(a, b) · Source, Examples
Returns an interpolator between the two dates a and b.
Note: no defensive copy of the returned date is created; the same Date instance is returned for every evaluation of the interpolator. No copy is made for performance reasons; interpolators are often part of the inner loop of animated transitions.
# d3.interpolateArray(a, b) · Source, Examples
Returns an interpolator between the two arrays a and b. If b is a typed array (e.g., Float64Array), interpolateNumberArray is called instead.
Internally, an array template is created that is the same length as b. For each element in b, if there exists a corresponding element in a, a generic interpolator is created for the two elements using interpolate. If there is no such element, the static value from b is used in the template. Then, for the given parameter t, the template’s embedded interpolators are evaluated. The updated array template is then returned.
For example, if a is the array [0, 1]
and b is the array [1, 10, 100]
, then the result of the interpolator for t = 0.5 is the array [0.5, 5.5, 100]
.
Note: no defensive copy of the template array is created; modifications of the returned array may adversely affect subsequent evaluation of the interpolator. No copy is made for performance reasons; interpolators are often part of the inner loop of animated transitions.
# d3.interpolateNumberArray(a, b) · Source, Examples
Returns an interpolator between the two arrays of numbers a and b. Internally, an array template is created that is the same type and length as b. For each element in b, if there exists a corresponding element in a, the values are directly interpolated in the array template. If there is no such element, the static value from b is copied. The updated array template is then returned.
Note: For performance reasons, no defensive copy is made of the template array and the arguments a and b; modifications of these arrays may affect subsequent evaluation of the interpolator.
# d3.interpolateObject(a, b) · Source, Examples
Returns an interpolator between the two objects a and b. Internally, an object template is created that has the same properties as b. For each property in b, if there exists a corresponding property in a, a generic interpolator is created for the two elements using interpolate. If there is no such property, the static value from b is used in the template. Then, for the given parameter t, the template's embedded interpolators are evaluated and the updated object template is then returned.
For example, if a is the object {x: 0, y: 1}
and b is the object {x: 1, y: 10, z: 100}
, the result of the interpolator for t = 0.5 is the object {x: 0.5, y: 5.5, z: 100}
.
Object interpolation is particularly useful for dataspace interpolation, where data is interpolated rather than attribute values. For example, you can interpolate an object which describes an arc in a pie chart, and then use d3.arc to compute the new SVG path data.
Note: no defensive copy of the template object is created; modifications of the returned object may adversely affect subsequent evaluation of the interpolator. No copy is made for performance reasons; interpolators are often part of the inner loop of animated transitions.
# d3.interpolateTransformCss(a, b) · Source, Examples
Returns an interpolator between the two 2D CSS transforms represented by a and b. Each transform is decomposed to a standard representation of translate, rotate, x-skew and scale; these component transformations are then interpolated. This behavior is standardized by CSS: see matrix decomposition for animation.
# d3.interpolateTransformSvg(a, b) · Source, Examples
Returns an interpolator between the two 2D SVG transforms represented by a and b. Each transform is decomposed to a standard representation of translate, rotate, x-skew and scale; these component transformations are then interpolated. This behavior is standardized by CSS: see matrix decomposition for animation.
# d3.interpolateZoom(a, b) · Source, Examples
Returns an interpolator between the two views a and b of a two-dimensional plane, based on “Smooth and efficient zooming and panning” by Jarke J. van Wijk and Wim A.A. Nuij. Each view is defined as an array of three numbers: cx, cy and width. The first two coordinates cx, cy represent the center of the viewport; the last coordinate width represents the size of the viewport.
The returned interpolator exposes a duration property which encodes the recommended transition duration in milliseconds. This duration is based on the path length of the curved trajectory through x,y space. If you want a slower or faster transition, multiply this by an arbitrary scale factor (V as described in the original paper).
# interpolateZoom.rho(rho) · Source
Given a zoom interpolator, returns a new zoom interpolator using the specified curvature rho. When rho is close to 0, the interpolator is almost linear. The default curvature is sqrt(2).
# d3.interpolateDiscrete(values) · Source, Examples
Returns a discrete interpolator for the given array of values. The returned interpolator maps t in [0, 1 / n) to values[0], t in [1 / n, 2 / n) to values[1], and so on, where n = values.length. In effect, this is a lightweight quantize scale with a fixed domain of [0, 1].
# d3.quantize(interpolator, n) · Source, Examples
Returns n uniformly-spaced samples from the specified interpolator, where n is an integer greater than one. The first sample is always at t = 0, and the last sample is always at t = 1. This can be useful in generating a fixed number of samples from a given interpolator, such as to derive the range of a quantize scale from a continuous interpolator.
Caution: this method will not work with interpolators that do not return defensive copies of their output, such as d3.interpolateArray, d3.interpolateDate and d3.interpolateObject. For those interpolators, you must wrap the interpolator and create a copy for each returned value.
# d3.interpolateRgb(a, b) · Source, Examples
Or, with a corrected gamma of 2.2:
Returns an RGB color space interpolator between the two colors a and b with a configurable gamma. If the gamma is not specified, it defaults to 1.0. The colors a and b need not be in RGB; they will be converted to RGB using d3.rgb. The return value of the interpolator is an RGB string.
# d3.interpolateRgbBasis(colors) · Source, Examples
Returns a uniform nonrational B-spline interpolator through the specified array of colors, which are converted to RGB color space. Implicit control points are generated such that the interpolator returns colors[0] at t = 0 and colors[colors.length - 1] at t = 1. Opacity interpolation is not currently supported. See also d3.interpolateBasis, and see d3-scale-chromatic for examples.
# d3.interpolateRgbBasisClosed(colors) · Source, Examples
Returns a uniform nonrational B-spline interpolator through the specified array of colors, which are converted to RGB color space. The control points are implicitly repeated such that the resulting spline has cyclical C² continuity when repeated around t in [0,1]; this is useful, for example, to create cyclical color scales. Opacity interpolation is not currently supported. See also d3.interpolateBasisClosed, and see d3-scale-chromatic for examples.
# d3.interpolateHsl(a, b) · Source, Examples
Returns an HSL color space interpolator between the two colors a and b. The colors a and b need not be in HSL; they will be converted to HSL using d3.hsl. If either color’s hue or saturation is NaN, the opposing color’s channel value is used. The shortest path between hues is used. The return value of the interpolator is an RGB string.
# d3.interpolateHslLong(a, b) · Source, Examples
Like interpolateHsl, but does not use the shortest path between hues.
# d3.interpolateLab(a, b) · Source, Examples
Returns a CIELAB color space interpolator between the two colors a and b. The colors a and b need not be in CIELAB; they will be converted to CIELAB using d3.lab. The return value of the interpolator is an RGB string.
# d3.interpolateHcl(a, b) · Source, Examples
Returns a CIELChab color space interpolator between the two colors a and b. The colors a and b need not be in CIELChab; they will be converted to CIELChab using d3.hcl. If either color’s hue or chroma is NaN, the opposing color’s channel value is used. The shortest path between hues is used. The return value of the interpolator is an RGB string.
# d3.interpolateHclLong(a, b) · Source, Examples
Like interpolateHcl, but does not use the shortest path between hues.
# d3.interpolateCubehelix(a, b) · Source, Examples
Or, with a gamma of 3.0 to emphasize high-intensity values:
Returns a Cubehelix color space interpolator between the two colors a and b using a configurable gamma. If the gamma is not specified, it defaults to 1.0. The colors a and b need not be in Cubehelix; they will be converted to Cubehelix using d3.cubehelix. If either color’s hue or saturation is NaN, the opposing color’s channel value is used. The shortest path between hues is used. The return value of the interpolator is an RGB string.
# d3.interpolateCubehelixLong(a, b) · Source, Examples
Or, with a gamma of 3.0 to emphasize high-intensity values:
Like interpolateCubehelix, but does not use the shortest path between hues.
# interpolate.gamma(gamma)
Given that interpolate is one of interpolateRgb, interpolateCubehelix or interpolateCubehelixLong, returns a new interpolator factory of the same type using the specified gamma. For example, to interpolate from purple to orange with a gamma of 2.2 in RGB space:
const interpolator = d3.interpolateRgb.gamma(2.2)("purple", "orange");
See Eric Brasseur’s article, Gamma error in picture scaling, for more on gamma correction.
# d3.interpolateHue(a, b) · Source, Examples
Returns an interpolator between the two hue angles a and b. If either hue is NaN, the opposing value is used. The shortest path between hues is used. The return value of the interpolator is a number in [0, 360).
Whereas standard interpolators blend from a starting value a at t = 0 to an ending value b at t = 1, spline interpolators smoothly blend multiple input values for t in [0,1] using piecewise polynomial functions. Only cubic uniform nonrational B-splines are currently supported, also known as basis splines.
# d3.interpolateBasis(values) · Source, Examples
Returns a uniform nonrational B-spline interpolator through the specified array of values, which must be numbers. Implicit control points are generated such that the interpolator returns values[0] at t = 0 and values[values.length - 1] at t = 1. See also d3.curveBasis.
# d3.interpolateBasisClosed(values) · Source, Examples
Returns a uniform nonrational B-spline interpolator through the specified array of values, which must be numbers. The control points are implicitly repeated such that the resulting one-dimensional spline has cyclical C² continuity when repeated around t in [0,1]. See also d3.curveBasisClosed.
# d3.piecewise([interpolate, ]values) · Source, Examples
Returns a piecewise interpolator, composing interpolators for each adjacent pair of values. The returned interpolator maps t in [0, 1 / (n - 1)] to interpolate(values[0], values[1]), t in [1 / (n - 1), 2 / (n - 1)] to interpolate(values[1], values[2]), and so on, where n = values.length. In effect, this is a lightweight linear scale. For example, to blend through red, green and blue:
const interpolate = d3.piecewise(d3.interpolateRgb.gamma(2.2), ["red", "green", "blue"]);
If interpolate is not specified, defaults to d3.interpolate.
FAQs
Interpolate numbers, colors, strings, arrays, objects, whatever!
The npm package d3-interpolate receives a total of 6,227,890 weekly downloads. As such, d3-interpolate popularity was classified as popular.
We found that d3-interpolate demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.