SVG标签

发布时间 2023-10-03 14:48:15作者: 樱桃树下的约定

SVG 有一些预定义的形状元素

  • 矩形 <rect>
  • 圆形 <circle>
  • 椭圆 <ellipse>
  • 线 <line>
  • 折线 <polyline>
  • 多边形 <polygon>
  • 路径 <path>

矩形 - <rect>

<svg width="400" height="180">
  <rect x="50" y="20" width="150" height="150"
  style="fill:blue;stroke:pink;stroke-width:5;fill-opacity:0.1;stroke-opacity:0.9" />
</svg>
  • x 属性定义矩形的左侧位置(例如,x="0" 定义矩形到浏览器窗口左侧的距离是 0px)
  • y 属性定义矩形的顶端位置(例如,y="0" 定义矩形到浏览器窗口顶端的距离是 0px)
  • CSS 的 fill-opacity 属性定义填充颜色透明度(合法的范围是:0 - 1)
  • CSS 的 stroke-opacity 属性定义轮廓颜色的透明度(合法的范围是:0 - 1)
 

圆形- <circle>

<svg height="100" width="100">
  <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
</svg>
  • cx 和 cy 属性定义圆点的 x 和 y 坐标。如果省略 cx 和 cy,圆的中心会被设置为(0, 0)
  • r 属性定义圆的半径
 

椭圆 - <ellipse>

<svg height="140" width="500">
  <ellipse cx="200" cy="80" rx="100" ry="50"
  style="fill:yellow;stroke:purple;stroke-width:2" />
</svg>
  • CX 属性定义的椭圆中心的x坐标
  • CY 属性定义的椭圆中心的y坐标
  • RX 属性定义的水平半径
  • RY 属性定义的垂直半径

线条 - <line>

<svg height="210" width="500">
  <line x1="0" y1="0" x2="200" y2="200" style="stroke:rgb(255,0,0);stroke-width:2" />
</svg>
  • x1 属性在 x 轴定义线条的开始
  • y1 属性在 y 轴定义线条的开始
  • x2 属性在 x 轴定义线条的结束
  • y2 属性在 y 轴定义线条的结束

折线 - <polyline>

<svg height="200" width="500">
  <polyline points="20,20 40,25 60,40 80,120 120,140 200,180"
  style="fill:none;stroke:black;stroke-width:3" />
</svg>
  • points 点属性定义绘制多段线所需的点列表(x和y坐标对)

多边形 - <polygon>

五角星 ☆
<polygon> 标签用来创建含有不少于三个边的图形。
多边形是由直线组成,其形状是"封闭"的(所有的线条连接起来)。
points 属性定义多边形每个角的 x 和 y 坐标
<svg height="210" width="500">
  <polygon points="100,10 40,198 190,78 10,78 160,198"
  style="fill:lime;stroke:purple;stroke-width:5;fill-rule:nonzero;" />
</svg>
  • 'height' 和 'width':这些属性定义了SVG图形的大小。在这个例子中,SVG图形的高度是210,宽度是500。
  • 'polygon':是一个多边形元素,这些点由 'points' 属性指定,遵循 'x1,y1 x2,y2 ...' 的格式。在这个例子中,多边形的点是 (100,10), (40,198), (190,78), (10,78), 和 (160,198)。
  • 'style':这个属性用于定义SVG元素的CSS样式。在这个例子中,多边形被填充为绿色('fill:lime'),边框为紫色('stroke:purple'),宽度为5('stroke-width:5'),并且填充规则为非零('fill-rule:nonzero')
 

路径 - <path>

<svg height="210" width="400">
  <path d="M150 0 L75 200 L225 200 Z" />
</svg>
开始于位置150 0,到达位置75 200,然后从那里开始到225 200,最后在150 0关闭路径
  • M = 移动到
  • L = lineto
  • H = 水平线到
  • V = 垂直线到
  • C = 曲线
  • S = 平滑曲线到
  • Q = 二次贝塞尔曲线
  • T = 平滑二次贝塞尔曲线
  • A = 椭圆弧
  • Z = 关闭路径

注释: 以上所有命令均允许小写字母。大写表示绝对定位,小写表示相对定位。