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:
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.
You can do it with a linearGradient, if you set the stop colours such that the gradient is an instant change in colour at the stops. E.g.
<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>
Alternatively, and perhaps more simply, you could dynamically create 3 rects with 3 different fills. If you put the rectangles as children of a <g>
element you can set a transform on the <g>
element and it will position all the rectangles together wherever you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With