HTML5如何使用SVG的方法示例

2020-04-25 07:54:16易采站长站整理

如果不指定width属性和height属性,只指定viewBox属性,则相当于只给定 SVG 图像的长宽比。这时,SVG 图像的默认大小将等于所在的 HTML 元素的大小。

2.

<circle>
标签

<circle>
标签代表圆形。


<svg width="300" height="180">
<circle cx="30" cy="50" r="25" />
<circle cx="90" cy="50" r="25" class="red" />
<circle cx="150" cy="50" r="25" class="fancy" />
</svg>

上面的代码定义了三个圆。

<circle>
标签的cx、cy、r属性分别为横坐标、纵坐标和半径,单位为像素。坐标都是相对于
<svg>
画布的左上角原点。

class属性用来指定对应的 CSS 类。


.red {
fill: red;
}

.fancy {
fill: none;
stroke: black;
stroke-width: 3pt;
}

SVG 的 CSS 属性与网页元素有所不同。

fill:填充色
stroke:描边色
stroke-width:边框宽度

3.

<line>
标签

<line>
标签用来绘制直线。


<svg width="300" height="180">
<line x1="0" y1="0" x2="200" y2="0" style="stroke:rgb(0,0,0);stroke-width:5" />
</svg>

上面代码中,<line>标签的x1属性和y1属性,表示线段起点的横坐标和纵坐标;x2属性和y2属性,表示线段终点的横坐标和纵坐标;style属性表示线段的样式。

4.

<polyline>
标签

<polyline>
标签用于绘制一根折线。


<svg width="300" height="180">
<polyline points="3,3 30,28 3,53" fill="none" stroke="black" />
</svg>

<polyline>
的points属性指定了每个端点的坐标,横坐标与纵坐标之间与逗号分隔,点与点之间用空格分隔。

5.

<rect>
标签

<rect>
标签用于绘制矩形。


<svg width="300" height="180">
<rect x="0" y="0" height="100" width="200" style="stroke: #70d5dd; fill: #dd524b" />