I can draw a spline using d3 without a problem.
<html>
<head>
<script src="https://d3js.org/d3.v7.min.js"></script>
<style>
.graph-container {
width: 100%;
height: 800px;
position: relative;
}
</style>
</head>
<body>
<div id="graph-container" class="graph-container"></div>
<script>
// Define the data points for the spline curve
const data = [
{ x: 0, y: 80, r: 12 },
{ x: 100, y: 100, r: 40 },
{ x: 200, y: 30, r: 6 },
{ x: 300, y: 50, r: 8 },
{ x: 400, y: 40, r: 10 },
{ x: 500, y: 80, r: 12 },
];
// Set up the SVG container
const svgWidth = 600;
const svgHeight = 200;
const svg = d3.select('#graph-container') // Select the graph-container div
.append('svg')
.attr('width', svgWidth)
.attr('height', svgHeight);
// Create the spline generator
const line = d3.line()
.x((d) => d.x)
.y((d) => d.y)
// .curve(d3.curveMonotoneX);
.curve(d3.curveCardinal);
// Draw the spline curve
svg.append('path')
.datum(data)
.attr('d', line)
.attr('fill', 'none')
.attr('stroke', 'green')
.attr('stroke-width', (d) => d.r);
</script>
</body>
</html>
My problem is to draw each segment with a different thickness (stroke width). I want each line segment to transition to the next control point smoothly.
It seems that d3 .attr(‘stroke-width’, (d) => d.r) doesn’t work.
How can I do it in React JS?
Thanks,
2
Answers
Here is a spline built as an approximated multiline:
Based on Michael Rovinsky’s
rValueByX()
interpolation helper you could also draw 2 Splines and concatenate them.We’re actually drawing an upper and a bottom spline using an y offset according to the current
r
stroke radius.The bottom spline needs to reverse the data coordinates.
Then we can concatenate both splines to a single path:
The benefit of this approach – we don’t need to approximate the shape by many
<line>
elements.Worth mentioning: Hundreds of
getPointAtLength()
calls can significantly impact rendering performance.