You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

D3图表:如何为SVG路径添加描边样式

Adding Stroke Styles to Your D3 Path

Hey there! Adding stroke styles to your D3-generated SVG path is super simple—you just need to chain additional style or attribute calls right onto your existing code. Let me show you how to adjust your snippet:

Option 1: Using CSS Styles with .style()

This approach works great if you prefer CSS-like syntax, and it plays nicely with dynamic values based on your data:

path = group.append("svg:path")
  .attr("d", arc)
  .style("fill", function(d) { 
    if (d.children) return color(d.name) 
    else return "grey" 
  })
  // Add stroke styles here
  .style("stroke", "#222") // Solid dark gray stroke color
  .style("stroke-width", "1.5px") // Set stroke thickness
  .style("stroke-opacity", 0.8) // Optional: adjust stroke transparency
  .attr("display", function(d) { return d.depth ? null : "none"; })
  .each(stash);

Option 2: Using SVG Attributes with .attr()

If you’d rather set direct SVG attributes (which is also fully valid), use .attr() instead:

path = group.append("svg:path")
  .attr("d", arc)
  .style("fill", function(d) { 
    if (d.children) return color(d.name) 
    else return "grey" 
  })
  // SVG attribute-based stroke settings
  .attr("stroke", "#222")
  .attr("stroke-width", 1.5)
  .attr("stroke-opacity", 0.8)
  .attr("display", function(d) { return d.depth ? null : "none"; })
  .each(stash);

Dynamic Stroke Based on Data

Just like your fill color, you can make the stroke dynamic too! For example, use different stroke colors for parent vs. leaf nodes:

.style("stroke", function(d) {
  return d.children ? "#000" : "#666"; // Black for parent nodes, light gray for leaves
})

The core idea here is leveraging D3’s method chaining—you can keep adding .style() or .attr() calls in sequence to set all the visual properties you need.

内容的提问来源于stack exchange,提问作者Jimmy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:07:11