4

I want to create svg rectangles dynamically with javascript. Those rectangles should be kind of a 2D diagramm bar filled with multiple background colors just like so:

enter image description here

Does there exist any shape for svg which can handle multiple background colors ? I do not want to use multiple rectangles and try to position them...

Event better would be if there would exist kind of a stackpanel where I can put into child elements...

because then I would like to bind those elements to knockoutjs.

4

1 回答 1

9

您可以使用线性渐变来完成,如果您设置停止颜色,使渐变是停止处颜色的即时变化。例如

<svg xmlns="http://www.w3.org/2000/svg">

    <defs>
      <linearGradient id="MyGradient" x2="0%" y2="100%">
        <stop offset="33%" stop-color="white" />
        <stop offset="33%" stop-color="#FF6" />
        <stop offset="66%" stop-color="#FF6" />
        <stop offset="66%" stop-color="#F60" />
      </linearGradient>
    </defs>

    <rect fill="url(#MyGradient)" stroke="black" stroke-width="5"  
          x="100" y="100" width="200" height="600"/>
</svg>

或者,也许更简单,您可以动态创建具有 3 种不同填充的 3 个矩形。如果将矩形作为元素的子<g>元素,则可以在元素上设置变换,<g>它将所有矩形放在您想要的任何位置。

于 2013-06-11T20:32:44.543 回答