简体   繁体   English

如何根据角度指定svg线性渐变

[英]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. 我想以一种精确复制CSS线性渐变行为的方式指定SVG线性渐变。 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. 例如,在CSS渐变中,您可以指定渐变开始和结束分别位于框的左上角和右下角。 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. 在我的第一次尝试中,我通过指定角度并通过计算框大小的x1,y1,x2,y2坐标来复制带SVG的CSS线性渐变。 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). 现在,这适用于一个大小的盒子(300,100),但你会发现我必须指定旋转中心的绝对值(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 . SVG仅允许根据绝对坐标指定梯度变换旋转原点。 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. 您需要使用JavaScript动态设置旋转原点,以便执行我认为您要执行的操作:旋转渐变,还可以使颜色停止在包含框内均匀分布。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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