Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a svg rectangle filled with different background color by percentage or pixel

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.

like image 520
Elisabeth Avatar asked Feb 16 '23 06:02

Elisabeth


1 Answers

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.

like image 67
Robert Longson Avatar answered Apr 27 '23 04:04

Robert Longson