如何通过一个渐变填充多个svg路径?

时间:2018-11-01 12:57:06

标签: html css svg path gradient

有一个示例,其中包含两个路径,每个路径均由渐变填充。

<svg height="1000" width="1400">
    <defs>
      <linearGradient id="lingrad" x1="0%" y1="0%" x2="100%" y2="0%">
        <stop offset="0%" stop-color="red" />
        <stop offset="100%" stop-color="green" />
      </linearGradient>
    </defs>

    <g fill="url(#lingrad)">
      <path d="M501.333,490.667H10.667C4.779,490.667,0,495.445,0,501.333C0,507.221,4.779,512,10.667,512h490.667
        c5.888,0,10.667-4.779,10.667-10.667C512,495.445,507.221,490.667,501.333,490.667z"/>

      <path d="M96,362.667H32c-5.888,0-10.667,4.779-10.667,10.667v128C21.333,507.221,26.112,512,32,512h64
        c5.888,0,10.667-4.779,10.667-10.667v-128C106.667,367.445,101.888,362.667,96,362.667z M85.333,490.667H42.667V384h42.667
        V490.667z"/>
    </g>
  </svg>

但是每个路径都由自己的渐变填充。

如何用一个共享渐变填充所有路径?

2 个答案:

答案 0 :(得分:2)

只需创建一条路径即可。
只需将一个路径的d标签添加到另一路径的d标签中即可:

<path d="M501.333,490.667H10.667C4.779,490.667,0,495.445,0,501.333C0,507.221,4.779,512,10.667,512h490.667
        c5.888,0,10.667-4.779,10.667-10.667C512,495.445,507.221,490.667,501.333,490.667z"/>

<path d="M96,362.667H32c-5.888,0-10.667,4.779-10.667,10.667v128C21.333,507.221,26.112,512,32,512h64
        c5.888,0,10.667-4.779,10.667-10.667v-128C106.667,367.445,101.888,362.667,96,362.667z M85.333,490.667H42.667V384h42.667
        V490.667z"/>

<svg height="1000" width="1400">
  <defs>
    <linearGradient id="lingrad" x1="0%" y1="0%" x2="100%" y2="0%">
      <stop offset="0%" stop-color="red" />
      <stop offset="100%" stop-color="green" />
    </linearGradient>
  </defs>

    <g fill="url(#lingrad)">
        <path d="M501.333,490.667H10.667C4.779,490.667,0,495.445,0,501.333C0,507.221,4.779,512,10.667,512h490.667
            c5.888,0,10.667-4.779,10.667-10.667C512,495.445,507.221,490.667,501.333,490.667zM96,362.667H32c-5.888,0-10.667,4.779-10.667,10.667v128C21.333,507.221,26.112,512,32,512h64
            c5.888,0,10.667-4.779,10.667-10.667v-128C106.667,367.445,101.888,362.667,96,362.667z M85.333,490.667H42.667V384h42.667
            V490.667z"/>
    </g>
</svg>

答案 1 :(得分:0)

定义梯度尺寸,而不是相对于对象边界框(对于单个形状,默认为gradientUnits="objectBoundingBox"),而是相对于<g>元素({{1} }。

gradientUnits="userSpaceOnUse"