HTML5之SVG 2D入门5—颜色的表示及定义方式

2020-04-21 07:56:56易采站长站整理

fx,fy属性:定义颜色中心(焦点)处的位置,也就是渐变色最浓处的坐标,在上面例子中,红色最红的是圆心,这是默认效果;如果想改变一下,就可以设置fx,fy坐标值。
不过这里需要注意一下上面cx,cy,r,fx,fy的值,你会发现它们都是小数,那么单位是什么呢?
这个需要先了解另外一个相关的属性:gradientUnits,它定义了定义渐变色使用的坐标单位。这个属性有2个可用值:userSpaceOnUse和objectBoundingBox。

objectBoundingBox是默认值,它使用的坐标都是相对于对象包围盒的(方形包围盒,不是方形包围盒的情况比较复杂,略过),取值范围是0到1。例如上例中的cx,cy的坐标值(0.25,0.25)。意味着这个圆心是在包围盒的左上角1/4处,半径0.25意味着半径长是对象方形包围盒长的1/4,就像你们图中看到的那样。
userSpaceOnUse表示使用的是绝对坐标,使用这个设置的时候,你必须要保证渐变色和填充的对象要保持在一个位置。
再看下面这个例子,注意gradientUnits属性默认值是objectBoundingBox:

复制代码
<svg width=”120″ height=”120″>
<defs>
<radialGradient id=”Gradient5″
cx=”0.5″ cy=”0.5″ r=”0.5″ fx=”0.25″ fy=”0.25″>
<stop offset=”0%” stop-color=”red”/>
<stop offset=”100%” stop-color=”blue”/>
</radialGradient>
</defs>

<rect x=”10″ y=”10″ rx=”15″ ry=”15″ width=”100″ height=”100″
fill=”url(#Gradient5)” stroke=”black” stroke-width=”2″/>
<circle cx=”60″ cy=”60″ r=”50″ fill=”transparent” stroke=”white” stroke-width=”2″/>
<circle cx=”35″ cy=”35″ r=”2″ fill=”white” stroke=”white”/>
<circle cx=”60″ cy=”60″ r=”2″ fill=”white” stroke=”white”/>
<text x=”38″ y=”40″ fill=”white” font-family=”sans-serif” font-size=”10pt”>(fx,fy)</text>
<text x=”63″ y=”63″ fill=”white” font-family=”sans-serif” font-size=”10pt”>(cx,cy)</text>
</svg>

看效果图就知道"焦点"的含义了。

此外,还有渐变色元素还有一些变换的属性,如gradientTransform,这个不是这里的重点,后面会总结变换。