使用D3同时插值startAngle与endAngle,SVG红色部分无法双向动画
Solution for Bidirectional SVG Arc Animation with D3
Got it, let's get that bidirectional arc animation working! The issue with your current code is that you're only interpolating the endAngle—we need to animate both startAngle and endAngle at the same time to get that "spreading to both sides" effect.
Here's the Fixed Code
First, make sure you have your arc generator set up (I'll include that for context), then adjust the attrTween to interpolate both angles simultaneously using d3.interpolateObject:
// Define your arc generator first (adjust radii to match your use case) const arc = d3.arc() .innerRadius(80) .outerRadius(150); // Set your initial and target angles // Example: Start with a narrow arc, animate to spread left and right const initialStartAngle = Math.PI * 0.75; const initialEndAngle = Math.PI * 1.25; const targetStartAngle = Math.PI * 0.5; // Move start angle left const targetEndAngle = Math.PI * 1.5 - 0.03; // Move end angle right (keep your -0.03 offset) d3.select(selector) .datum({ startAngle: initialStartAngle, endAngle: initialEndAngle }) .transition() .delay(i * duration === 0 ? 0 : i * duration - 150) .duration(duration) .attrTween('d', function(d) { // Use interpolateObject to animate both angles at once const angleInterpolator = d3.interpolateObject( { startAngle: d.startAngle, endAngle: d.endAngle }, { startAngle: targetStartAngle, endAngle: targetEndAngle } ); return function(t) { // Get the interpolated angles for the current transition step const currentAngles = angleInterpolator(t); // Update the datum's angles d.startAngle = currentAngles.startAngle; d.endAngle = currentAngles.endAngle; // Return the updated arc path return arc(d); }; });
Key Changes Explained:
d3.interpolateObject: This function lets us interpolate multiple properties in an object at the same time. Instead of just tweening a single angle value, we tween an object containing bothstartAngleandendAngle, so they animate in sync.- Target Angle Setup: To get the bidirectional effect, set your
targetStartAngleto a smaller value (moving the left edge of the arc outward) andtargetEndAngleto a larger value (moving the right edge outward). Adjust these values to match exactly how wide you want the arc to spread. - Keep Your Delay Logic: I kept your existing delay calculation since that's probably for staggering multiple arcs—no need to change that unless you want to adjust the timing.
This will make your red SVG arc smoothly animate outward to both sides instead of just expanding in one direction.
内容的提问来源于stack exchange,提问作者Debasish Pothal
相关产品推荐
相关产品推荐

