How may I use 'inline' SVG gradient on an element like <line>?

梦想与她 提交于 2019-12-01 05:18:28

You could use a data URI i.e. fill="url(data:image/svg+xml;base64,...encoded full svg...#mygradient)"

Here's an example: http://xn--dahlstrm-t4a.net/svg/paint/datauri-gradient.svg

First of all, I probably should have thought of this before asking the question at all, but my excuse is that I'm still learning svg. And my suggested answer is probably not the fully correct either. See code example at bottom with SVG Params which probably is the best solution and not having to keep track of a changing link reference to a gradient.

I however solved my issue with wrapping the following code inside a <g> for every link/line I draw as shown below:

  <linearGradient id="gradientForLoopi" x1="0%" y1="0%" x2="0%" y2="100%">
      <stop offset="0%" style="stop-color:#000066;stop-opacity:1" />
      <stop offset="50%" style="stop-color:#000066;stop-opacity:1" />
      <stop offset="51%" style="stop-color:#00ffff;stop-opacity:1" />
      <stop offset="100%" style="stop-color:#00ffff;stop-opacity:1" />
  </linearGradient>
  <line stroke="url(#gradientForLoopi)" x1="130.8757632890282"
     y1="163.6818288670081" x2="651.9483366457684" y2="415.704113030817" />

(I probably didn't even need to do that either, but I did for the semantic purposes so I could work with d3js more easily).

Doing some more research on the field, a better solution would be to use SVG Params (draft as pr. writing) when it is commonly available in browsers with HTML5 doctype (only partly working with SVG context headers(?), and not inline <svg> inside a HTML5 document) See demo with HTML5 doctype not working, and the same <svg>-content with svg content-type/.svg working as it should here.

You can probably already now use the SVG Params draft using a prototyping script, which I didn't get to work and probably doesn't work in 'all common browsers'-yet.

With SVG Params you would simply do something along the lines (I assume):

<defs>
    <linearGradient id="linkload" x1="0%" y1="0%" x2="0%" y2="100%">
        <stop offset="0%" style="stop-color:param(uplink_color);stop-opacity:1" />
          <stop offset="50%" style="stop-color:param(uplink_color);stop-opacity:1" />
          <stop offset="51%" style="stop-color:param(downlink_color);stop-opacity:1" />
          <stop offset="100%" style="stop-color:param(downlink_color);stop-opacity:1" />
    </linearGradient>
    <line stroke="url(#linkload)" x1="param(x1)"
        y1="param(y1)" x2="param(x2)" y2="param(y2)" />
</defs>

<use id="linkid" xlink:href="#linkload" x1="300" x2="0" y1="0" y2="300">
    <param name="downlink_color" value="#00ffff" />
    <param name="uplink_color" value="#006666" />
</use>
<use id="linkid" .. for every link..
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!