分享

SVG线性渐变色 | WEB知识

 537q60d4uhwd3e 2020-01-10

渐变色(gradient)是指从一种颜色平滑的过渡到另外一种颜色。而且,我们可以将多种渐变色应用到同一个网页元素上。

在SVG里,有两种主要的渐变色类型:

  • 线性渐变色 Linear

  • 辐射式(放射式)渐变色 Radial


SVG线性渐变色 – <linearGradient>

<linearGradient>标记就是用来定义渐变色的。

<linearGradient>标记必须放在<defs>标记内。<defs>标记就是“definitions”单词的简写,用来容纳其它各种SVG标记。

线性渐变色可以定义成水平渐变色,垂直渐变色和斜向渐变色:

  • y1y2相等,而x1x2不等时,就形成了水平渐变色

  • y1y2不等,而x1x2相等时,就形成了垂直渐变色

  • y1y2不等,而x1x2也不等时,就形成了斜向渐变色


例 1

我们先定义一个椭圆,而后用一个从黄色到红色的渐变色渲染它:

上面的图像使用了下面的SVG代码:

<svg height='150' width='400'> <defs>   <linearGradient id='grad1' x1='0%' y1='0%' x2='100%' y2='0%'>     <stop offset='0%' style='stop-color:rgb(255,255,0);stop-opacity:1' />     <stop offset='100%' style='stop-color:rgb(255,0,0);stop-opacity:1' />   </linearGradient> </defs> <ellipse cx='200' cy='70' rx='85' ry='55'fill='url(#grad1)' /></svg>

代码说明:

  • <linearGradient>标记的id属性定义了这个渐变色的唯一标志

  • <linearGradient>标记的x1, x2, y1,y2四个属性定义了渐变色的起始位置和终止位置

  • 渐变色的颜色组成可以是2个或2个以上的颜色。每种颜色都使用一个<stop>标记定义。offset属性用来定义渐变色的开始和结束位置。

  • fill属性定义了需要引用的渐变色的ID


例 2

下面的例子中的渐变色方向是垂直的:

上面的图像使用了下面的SVG代码:

<svg height='150' width='400'> <defs>   <linearGradient id='grad2' x1='0%' y1='0%' x2='0%' y2='100%'>     <stop offset='0%' style='stop-color:rgb(255,255,0);stop-opacity:1' />     <stop offset='100%' style='stop-color:rgb(255,0,0);stop-opacity:1' />   </linearGradient> </defs> <ellipse cx='200' cy='70' rx='85' ry='55' fill='url(#grad2)' /></svg>

例 3

下面的例子里,我们使用了水平渐变色,并且还在椭圆里添加了文字:

上面的图像使用了下面的SVG代码:

<svg height='150' width='400'> <defs>   <linearGradient id='grad3' x1='0%' y1='0%' x2='100%' y2='0%'>     <stop offset='0%' style='stop-color:rgb(255,255,0);stop-opacity:1' />     <stop offset='100%' style='stop-color:rgb(255,0,0);stop-opacity:1' />   </linearGradient> </defs> <ellipse cx='200' cy='70' rx='85' ry='55'fill='url(#grad3)' />  <text fill='#ffffff' font-size='45' font-family='Verdana' x='150' y='86'>  SVG</text></svg>

代码说明:

  • <text>标记的作用是添加一段文字




WEBHEK is optimized for learning, testing, and training. Examples might be simplified to improve reading and basic understanding.Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content.

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多