Published
Edited
Jan 20, 2021
4 stars
Insert cell
md`# Path Gradient`
Insert cell
chart = {
const svg = d3
.create("svg")
.attr("viewBox", [-width / 2, -height / 2, width, height])
.style("background", "aliceblue");

const p1 = { x: -400, y: 110 };
const p2 = { x: 400, y: -110 };
const cx = { x: 0, y: 0 };
let path = generatePath(p1, p2, cx);

const defs = svg.append('defs');
const gradient = defs
.append('linearGradient')
.attr("id", "gradient")
.attr("x1", path._x0)
.attr("y1", path._y0)
.attr("x2", path._x1)
.attr("y2", path._y1)
.attr("gradientUnits", "userSpaceOnUse");

gradient
.append("stop")
.attr("offset", "0")
.attr("stop-color", "red");

gradient
.append("stop")
.attr("offset", "1")
.attr("stop-color", "green");

const shape = svg
.append("path")
.attr("d", path)
.attr("stroke", "url(#gradient)")
.attr("stroke-width", "5")
.attr("fill", "none");

const starter = svg
.append("circle")
.attr("r", "5")
.attr("cx", p1.x)
.attr("cy", p1.y)
.attr("fill", "red")
.call(drag(p1));

const center = svg
.append("circle")
.attr("r", "5")
.attr("cx", cx.x)
.attr("cy", cx.y)
.attr("fill", "black")
.call(drag(cx));

const terminator = svg
.append("circle")
.attr("r", "5")
.attr("cx", p2.x)
.attr("cy", p2.y)
.attr("fill", "green")
.call(drag(p2));

function drag(point) {
return d3.drag().on("drag", function(event, d) {
point.x = event.x;
point.y = event.y;

d3.select(this)
.raise()
.attr("cx", point.x)
.attr("cy", point.y);

path = generatePath(p1, p2, cx);

gradient
.attr("x1", path._x0)
.attr("y1", path._y0)
.attr("x2", path._x1)
.attr("y2", path._y1);

shape.attr("d", path);
});
}

return svg.node();
}
Insert cell
Insert cell
height = 600
Insert cell
d3 = require("d3@6")
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