将渐变应用于SVG元素内的多个元素

时间:2012-01-13 02:58:56

标签: javascript html css svg

我正在尝试使用SVG元素创建一个看起来像这样的箭头:

enter image description here

这是我的尝试:

enter image description here

正如您所见,渐变应用于 rect&我的SVG中的多边形有没有办法在SVG的顶部图像中复制渐变效果?

也许这是一种CSS方式吗?也许我必须使用路径或单个多边形元素来创建箭头而不是 rect &的多边形

<svg width="424" height="100">
    <defs>
        <radialGradient id="grad1" cx="50%" cy="50%" r="50%" fx="50%" fy="50%">
          <stop offset="0%" style="stop-color:rgb(255,255,255); stop-opacity:0" />
          <stop offset="100%" style="stop-color:rgb(13,20,93);  stop-opacity:1" />
        </radialGradient>
    </defs>

    <rect x="0" y="25" rx="0" ry="0" width="212" height="50" fill="url(#grad1)"> </rect>
    <polygon points="212,0 212,100 424,50" fill="url(#grad1)"></polygon>
</svg>

2 个答案:

答案 0 :(得分:4)

您可以通过对两个形状进行分组来“制作”单个路径,然后将渐变应用于组

<svg
 xmlns:svg="http://www.w3.org/2000/svg"
 xmlns="http://www.w3.org/2000/svg"
 xmlns:xlink="http://www.w3.org/1999/xlink"
 version="1.1"
 width="424"
 height="100"
 id="svg2996">
 <defs>
 <radialGradient cx="0.5" cy="0.5" r="0.5" fx="0.5" fy="0.5" id="grad1">
  <stop style="stop-color:#ffffff;stop-opacity:0" offset="0" />
  <stop style="stop-color:#0d145d;stop-opacity:1" offset="1" />
 </radialGradient>
 <radialGradient cx="212" cy="50" r="212" fx="212" fy="50" id="radialGradient3809" xlink:href="#grad1"
 gradientUnits="userSpaceOnUse"
 gradientTransform="matrix(1,0,0,0.23584906,0,38.207547)" />
 </defs>
 <g style="fill:url(#radialGradient3809);fill-opacity:1">
  <rect width="212" height="50" rx="0" ry="0" x="0" y="25" />
  <polygon points="424,50 212,0 212,100 " />
 </g>
</svg>

codepen

答案 1 :(得分:1)

我使用了两个渐变来尝试重新创建你想要做的事情。您可以调整渐变的中心以与形状的边缘对齐:

<svg width="424" height="100">
    <defs>
        <radialGradient id="grad1" cx="100%" cy="50%" r="100%" fx="100%" fy="50%">
          <stop offset="0%" style="stop-color:rgb(255,255,255); stop-opacity:0" />
          <stop offset="100%" style="stop-color:rgb(13,20,93);  stop-opacity:1" />
        </radialGradient>
        <radialGradient id="grad2" cx="0%" cy="50%" r="50%" fx="0%" fy="50%">
          <stop offset="0%" style="stop-color:rgb(255,255,255); stop-opacity:0" />
          <stop offset="100%" style="stop-color:rgb(13,20,93);  stop-opacity:1" />
        </radialGradient>
    </defs>
    <rect x="0" y="25" rx="0" ry="0" width="212" height="50" fill="url(#grad1)"> </rect>
    <polygon points="212,0 212,100 424,50" fill="url(#grad2)"></polygon>
</svg>

Demo

single polygon是否有问题?

<svg width="424" height="100">
    <defs>
        <radialGradient id="grad1" cx="50%" cy="50%" r="50%" fx="50%" fy="50%">
          <stop offset="0%" style="stop-color:rgb(255,255,255); stop-opacity:0" />
          <stop offset="100%" style="stop-color:rgb(13,20,93);  stop-opacity:1" />
        </radialGradient>
    </defs>

    <polygon points="212,0 212,25 0,25 0,75, 212,75 212,100 424,50" fill="url(#grad1)"></polygon>
</svg>