問題描述

是否可以為 SVG <path> 元素設置 backgound-image

例如,如果我將元素的 class 設置為 wall,那麼 CSS 樣式.wall {fill: red;}可以工作,但.wall{background-image: url(wall.jpg)}不是.wall {background-color: red;}

最佳解決方案

您可以將背景製作為 pattern

<defs>
  <pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
    <image xlink:href="wall.jpg" x="0" y="0" width="100" height="100" />
  </pattern>
</defs>

根據您的圖像調整寬度和高度,然後從路徑中引用它:

<path d="M5,50
         l0,100 l100,0 l0,-100 l-100,0
         M215,100
         a50,50 0 1 1 -100,0 50,50 0 1 1 100,0
         M265,50
         l50,100 l-100,0 l50,-100
         z"
  fill="url(#img1)" />

Working example

次佳解決方案

“robertc” 的答案是 svg – 這與 d3.js 路徑代碼使用的相似。我設法通過應用以下內容為 d3.js 路徑創建動態 def 。

我設法通過將其定義如下來使其工作

chart.append("defs")
     .append('pattern')
     .attr('id', 'locked2')
     .attr('patternUnits', 'userSpaceOnUse')
     .attr('width', 4)
     .attr('height', 4)
     .append("image")
     .attr("xlink:href", "locked.png")
     .attr('width', 4)
     .attr('height', 4);

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇