这是SVG系列目录:
前言
回顾前面,在上一篇文章我们学习了如何使用SVG中最强大的path路径进行图形绘制,在之前的一些例子中我们在绘制图形时使用了一些属性,例如stroke、fill,今天本篇将详细讲讲这些属性是怎么使用的。
fill
fill属性设置绘制图形中内部的颜色(默认为black),如果你不想填充色可以将fill值设置为none,例:
<rect x="10" y="10" width="50" height="50"></rect>
<rect x="70" y="10" width="50" height="50" fill="red"></rect>
<rect x="130" y="10" width="50" height="50" fill="rgb(91,158,86)"></rect>
fill-opacity属性设置填充颜色的透明度范围0-1,例:
<rect x="10" y="10" width="50" height="50"></rect>
<rect x="70" y="10" width="50" height="50" fill="red"></rect>
<rect x="130" y="10" width="50" height="50" fill="rgb(91,158,86)" fill-opacity="0.5"></rect>
stroke
stroke属性设置绘制图形的线条元素,例:
<rect x="10" y="10" width="50" height="50"></rect>
<rect x="70" y="10" width="50" height="50" fill="red" stroke="blue"></rect>
<rect x="130" y="10" width="50" height="50" fill="rgb(91,158,86)" stroke="rgb(165,101,43)"></rect>
stroke-opacity属性设置边框颜色的透明度范围0-1,例:
<rect x="10" y="10" width="50" height="50"></rect>
<rect x="70" y="10" width="50" height="50" fill="none" stroke="blue" stroke-opacity="0.2"></rect>
<rect x="130" y="10" width="50" height="50" fill="rgb(91,158,86)" stroke="rgb(165,101,43)"></rect>
stroke-linecap属性,设置边框终点的形状,参数分为:
butt用直边结束线段,它是常规做法,线段边界90度垂直于描边的方向、贯穿它的终点。square的效果差不多,但是会稍微超出实际路径的范围,超出的大小由stroke-width控制。round表示边框的终点是圆角,圆角的半径也是由stroke-width控制的。
stroke-linejoin属性,用来控制两条描边线段之间,用什么方式连接,参数分为:
miter是默认值,表示用方形画笔在连接处形成尖角round表示用圆角连接,实现平滑效果bevel,连接处会形成一个斜接
<polyline points="10 10 60 50 110 10" fill="none" stroke-width="7" stroke="red" stroke-linecap="butt"></polyline>
<polyline points="130 10 180 50 230 10" fill="none" stroke-width="7" stroke="red" stroke-linecap="square"></polyline>
<polyline points="250 10 300 50 350 10" fill="none" stroke-width="7" stroke="red" stroke-linecap="round"></polyline>
<polyline points="10 70 60 110 110 70" fill="none" stroke-width="7" stroke="red" stroke-linejoin="miter"></polyline>
<polyline points="130 70 180 110 230 70" fill="none" stroke-width="7" stroke="red" stroke-linejoin="round"></polyline>
<polyline points="250 70 300 110 350 70" fill="none" stroke-width="7" stroke="red" stroke-linejoin="bevel"></polyline>
除了在标签中定义属性之外,你也可以使用CSS来给绘制的图形进行填充和描边操作。语法和在html中使用css一样,稍微有不同之处是属性名要做一些改改,见下表
| CSS属性 | SVG属性 | 说明 |
|---|---|---|
| background-color | fill | 填充 / 背景颜色 |
| border | stroke | 描边线条颜色 |
图形标签内的
width、height以及路径的命令是不能使用css设置的,需要写在标签内
我们看下使用CSS的例子:
.zrect{
stroke: black;
fill: red;
}
<rect x="10" y="10" width="50" height="50" class="zrect"></rect>
像这样子,我们将一些属性写入样式中,在元素中绑定类即可。如果你很多个元素的属性是相同的,那么这是一个很好的选择!
最后
本篇文章讲述了SVG中基本图形的一些常用的扩展属性,以及使用CSS去修改图形的样式。
感谢你的阅读!
😀😀 关注我,不迷路! 😀😀