简体   繁体   中英

How to specify svg linear gradient in terms of an angle

I'd like to specify an SVG linear gradient in a way that exactly duplicates CSS linear-gradient behavior. In a CSS gradient, for example, you may specify that a gradient start and end at the top left and bottom right of a box respectively. When a box resizes, the background gradient adapts automatically to the new size.

In my first attempt, I duplicated a CSS linear-gradient with SVG, by specifying an angle and by calculating the x1,y1,x2,y2 coordinates from the box size. But if the box is resized, the angle of the gradient does not change and is no longer correct. (I would have to recalc all the coordinates).

My next attempt was to use a transform to rotate the gradient. Here's some code:

<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
  <linearGradient id="g1" gradientUnits="userSpaceOnUse" 
      gradientTransform="rotate(-45 150 50)">
    <stop stop-color="#FF0000" offset="0"/>
    <stop stop-color="#00FF00" offset="0.5"/>
    <stop stop-color="#0000FF" offset="1"/>
  </linearGradient>
  <rect x="0" y="0" width="100%" height="100%" fill="url(#g1)" />
</svg>

Now, this works for a box of size (300,100) but you'll see that I'm having to specify absolute values for the centre of rotation (150,50).

Can I specify the centre in terms of a percentage? In the end I want the angle of the gradient to adapt to the dimensions of the box.

SVG only allows gradient transform rotation origins to be specified in terms of absolute coordinates . You will need to set the rotation origin dynamically with JavaScript in order to do what I think you're looking to do: which is to rotate the gradient, but also have the color stops be evenly distributed within the containing box.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM