上一篇: HTML5 Canvas
下一篇: HTML5 MathML
HTML5 内联 SVG
创建一个简单的 SVG 图形
首先,在 HTML 文件中创建一个 svg
元素,然后添加一个简单的图形,如圆形。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>内联 SVG 教程</title> </head> <body> <svg width="600" height="400"> <circle cx="50" cy="50" r="40" fill="blue" /> </svg> </body> </html>
使用各种图形元素
SVG 支持多种图形元素,包括矩形、圆形、椭圆、线条等。以下是一些基本的绘图示例。
绘制矩形
使用 rect
元素绘制矩形。
<rect x="100" y="10" width="100" height="50" fill="red" />
绘制椭圆
使用 ellipse
元素绘制椭圆。
<ellipse cx="250" cy="50" rx="60" ry="40" fill="green" />
绘制线条
使用 line
元素绘制线段。
<line x1="300" y1="10" x2="400" y2="60" stroke="purple" stroke-width="4" />
使用路径元素
SVG 的 path
元素可以创建复杂的图形。以下是一个简单的路径示例。
<path d="M 10 100 L 50 150 Q 100 200 200 150 C 300 100 400 200 500 150" stroke="black" fill="none" stroke-width="3" />
添加文本和样式
使用 text
元素在 SVG 图形中添加文本,并通过 CSS 样式设置字体和颜色。
<text x="50" y="250" font-family="Arial" font-size="24" fill="orange">Hello, SVG!</text>
为 SVG 元素添加样式,可以在 style
标签内编写 CSS 规则,也可以使用行内样式。以下是一个使用内联样式的示例:
<circle cx="350" cy="250" r="30" style="fill: yellow; stroke: black; stroke-width: 2px;" />
图形变换
通过 transform
属性对 SVG 图形进行移动、缩放、旋转等操作。以下是一些变换示例:
平移
将图形向右平移100像素,向下平移50像素:
<rect x="10" y="10" width="50" height="50" fill="blue" transform="translate(100, 50)" />
缩放
将图形在水平方向上缩放2倍,在垂直方向上缩放0.5倍:
<ellipse cx="450" cy="250" rx="30" ry="60" fill="pink" transform="scale(2, 0.5)" />
旋转
将图形绕 (50, 50) 点顺时针旋转45度:
<rect x="10" y="10" width="50" height="50" fill="brown" transform="rotate(45, 50, 50)" />
使用动画元素
通过 animate
和 animateTransform
元素为 SVG 图形添加动画效果。以下是一个简单的动画示例:
<circle cx="50" cy="350" r="30" fill="purple"> <animate attributeName="r" from="30" to="60" dur="2s" repeatCount="indefinite" /> </circle>
总结
内联 SVG 是一种强大的在网页上创建矢量图形的方法。你可以使用各种图形元素、路径、文本和样式来绘制复杂的图案,还可以通过变换和动画实现丰富的视觉效果。学会使用内联 SVG 有助于提升你的前端开发技能,为用户带来更精彩的体验。