Abhishek Mukherjee
Abhishek Mukherjee

Reputation: 361

How to apply "background: repeating-linear-gradient" style for rect using d3.js

I'm having trouble to replicate repeating-linear-gradient styling for rect using d3.

eg: I have the following div style:

.colorbarssegment{ 
     background: repeating-linear-gradient( to right, 
                        #c0c0c0, #c0c0c0 4px, 
                        #c0c000 4px, #c0c000 8px, 
                        #00c0c0 8px, #00c0c0 12px, 
                        #00c000 12px, #00c000 16px, 
                        #c000c0 16px, #c000c0 20px, 
                        #c00000 20px, #c00000 24px, 
                        #0000c0 24px, #0000c0 28px);
 }

when I use the class in div like:

<div class="colorbarssegment" style="width: 200px; height: 20px;"></div>

it looks like : enter image description here

How can I apply the same style for rect in d3.js?

Upvotes: 3

Views: 1170

Answers (2)

kid
kid

Reputation: 153

Check out this fiddle! I think this solution will do what you require.

<svg width="500" height="240" version="1.1" xmlns="http://www.w3.org/2000/svg">
  <defs>
      <linearGradient id="Gradient2" x1="16%" x2="1%" y1="50%" y2="50%">
        <stop offset="0%" stop-color="#c0c0c0"/>
        <stop offset="20%" stop-color="#c0c000"/>
        <stop offset="40%" stop-color="#c0c000"/>
        <stop offset="60%" stop-color="#c000c0"/>
        <stop offset="80%" stop-color="#c00000"/>
        <stop offset="100%" stop-color="#0000c0"/>
      </linearGradient>
      <linearGradient id="repeat"xlink:href="#Gradient2"spreadMethod="repeat" />
      <style type="text/css"><![CDATA[
        #rect1 { fill: url(#repeat); }
        .stop1 { stop-color: #c0c0c0; }
        .stop2 { stop-color: #c0c000; }
        .stop3 { stop-color: #c0c000; }
        .stop4 { stop-color: #c000c0; }
        .stop5 { stop-color: #c00000; }
        .stop6 { stop-color: #0000c0; }
      ]]></style>
  </defs>

  <rect id="rect1" x="10" y="10" rx="15" ry="15" width="120" height="30"/>

Upvotes: 1

KWeiss
KWeiss

Reputation: 3144

You will have to define a pattern in your SVG as described on this page: https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Patterns

I have created a fiddle that has a pattern similar to what you need: http://jsfiddle.net/11k570ud/

After that, you give the rect the attribute:

fill="url(#yourPatternID)"

You can either include this in the svg code, or add it with D3.js. An explanation of how to do that can be found here (this post uses Gradients, but Patterns work in a very similar way).

Upvotes: 2

Related Questions