Published
Edited
Apr 5, 2022
1 star
Insert cell
Insert cell
{
const height = 300;
const svg = d3.create('svg')
.attr('viewBox', [0, 0, width, height]);

const circle = svg.append('circle')
.attr('cx', width / 2)
.attr('cy', height / 2)
.attr('r', 100);

const colors = ['yellow', 'salmon', 'red', 'salmon', 'yellow'];
const defs = svg.append('defs');
const linearGradient = defs.append('linearGradient')
.attr('id', 'linear-gradient');

// Define linear gradient attributes
linearGradient
.attr('x1', '0%')
.attr('y1', '0%')
.attr('x2', '100%')
.attr('y2', '0%')
.attr('spreadMethod', 'reflect'); // Spread method defines how the shape is filled beyond edges of the gradient
// We use reflect to mean that coordinates from 100% to 200% are a reflection
// of the colors between 0% and 100%.

// Append a stop for each color in the gradient
const getStopOffset = (d, i) => i / (colors.length - 1);
const getStopColor = d => d;
linearGradient.selectAll('.stop')
.data(colors)
.enter().append('stop')
.attr('offset', getStopOffset)
.attr('stop-color', getStopColor);

// Animate the x1 coordinate to go from 0% to 100%
linearGradient.append('animate')
.attr('attributeName', 'x1')
.attr('values', '0%;100%')
.attr('dur', '5s') // animation is 5s
.attr('repeatCount', 'indefinite'); // Animation repeats indefinitely
// Animate the x2 coordinate to go from 100% to 200%
linearGradient.append('animate')
.attr('attributeName', 'x2')
.attr('values', '100%;200%')
.attr('dur', '5s') // animation is 5s
.attr('repeatCount', 'indefinite'); // Animation repeats indefinitely

// Apply linear gradient as the circle's fill
circle.style('fill', 'url(#linear-gradient)');

return svg.node();
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more