簡體   English   中英

如何使用 d3 動態為 svg 中的路徑元素添加顏色並做出反應

[英]How to add color to a path element in an svg dynamically with d3 and react

我有一個 SVG 圖標:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
  <circle cx="12" cy="12" r="12" />
  <path class="svg-fill"
    d="M12,2A10,10,0,1,0,22,12,10,10,0,0,0,12,2Zm1,3.3,1.35-1a8,8,0,0,1,4.38,3.34L18.34,9,17,9.49,13,6.7Zm-3.35-1L11,5.3V6.7L7,9.49,5.66,9,5.27,7.69A8.1,8.1,0,0,1,9.65,4.35ZM7.08,17.11l-1.14.1A7.94,7.94,0,0,1,4,12c0-.12,0-.23,0-.35l1-.73,1.38.48,1.46,4.34Zm7.42,2.48a7.83,7.83,0,0,1-5,0L8.81,18.1,9.45,17h5.11l.64,1.11ZM14.27,15H9.73L8.38,11,12,8.44,15.63,11Zm3.79,2.21-1.14-.1-.79-1.37,1.46-4.34L19,10.93l1,.73c0,.11,0,.22,0,.34A7.94,7.94,0,0,1,18.06,17.21Z" />
</svg>

我正在嘗試使用以下方法在 D3 圖表上呈現:

  svg
    .append('image')
    .attr('xlink:href', MyIcon)

如何動態更改 svg 中路徑的顏色,因為我將從 function 運行 append 代碼,例如:

const renderIcon = (iconColor) => {
  svg
    .append('image')
    .attr('xlink:href', MyIcon)
    // code to apply color param to the icon path

}

找不到真正讓上述工作的好方法。 我最終找到的解決方案是在我的組件的 return 語句中的 svg 元素內的 defs 元素中定義我的圖標:

return (
<svg>
  <defs>
    <MyIcon color={myColor1} id="myIcon1" />
    <MyIcon color={myColor2} id="myIcon2" />
  </defs>
</svg>
)

MyIcon 看起來像這樣的地方:

<g fill={color} id={id}>
  // other svg elements
</g>

然后通過將use元素附加到svg元素並傳入圖標id屬性來使用它們:

svg.append('use').attr('href', '#myIcon1');
svg.append('use').attr('href', '#myIcon2');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM