如何在 HTML5 SVG 中绘制矩形?
SVG 是一种基于 XML 的标记语言,用于描述二维矢量图形。在视觉方面,SVG 本质上相当于 HTML 之于文本。
矩形通过 <rect> 元素绘制在屏幕上。矩形在屏幕上的位置和形状由六个基本属性决定。
语法
<rect x="x-axis co-ordinate" y="y-axis co-ordinate" width="length" height="length" rx="length" ry="length" style="style information" class="style class" > </rect>
属性
X - 左上角的 x 坐标。
Y - 左上角的 y 坐标。
width - 矩形的宽度。
height - 矩形的高度。
rx - x 轴的圆角。
ry - y 轴的圆角。
style - 指示内联样式。
描述类的外部样式。
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
示例 1
使用“svg <rect>”
在下面的示例中,我们使用 svg <rect> 来绘制一个矩形。
<!DOCTYPE html> <html> <body> <svg width="400" height="100"> <rect width="400" height="100" style="fill:rgb(0, 255, 255); stroke-width:6;stroke:rgb(255, 0, 0)" /> </svg> </body> </html>
执行上述脚本后,它将生成一个输出,其中包含一个在网页上绘制的填充有十六进制颜色的矩形。
示例 2
添加 x 和 y 属性
在下面的示例中,我们使用带有 x 和 y 属性的 svg <rect> 元素。
<!DOCTYPE html> <html> <body> <svg width="400" height="800"> <rect x="50" y="20" width="150" height="150" style="fill:blue;stroke:red;stroke-width:5;fill-opacity:0.4; stroke-opacity:0.9"/> </svg> </body> </html>
当脚本执行时,它将生成一个输出,其中包含一个填充为蓝色的矩形,并带有宽度和高度。
示例 3
添加 CSS opacity 属性
在下面的示例中,我们使用带有 css opacity 的 svg <rect> 元素。
<!DOCTYPE html> <html> <body> <svg width="450" height="250"> <rect x="55" y="25" width="155" height="160" style="fill:blue;stroke:pink;stroke-width:5;opacity:0.5" /> </svg> </body> </html>
执行上述脚本后,它将生成一个输出,其中包含一个在网页上绘制的,填充为蓝色且具有透明度的矩形。
示例 4
在 HTML5 SVG 中绘制矩形。
<!DOCTYPE html> <html> <head> <style> #svgelem { position: relative; left: 10%; -webkit-transform: translateX(-20%); -ms-transform: translateX(-20%); transform: translateX(-20%); } </style> <title>SVG</title> </head> <body> <h2>HTML5 SVG Rectangle</h2> <svg id="svgelem" width="300" height="200" xmlns="http://www.w3.org/2000/svg"> <rect width="200" height="100" fill="green"/> </svg> </body> </html>
当脚本执行时,输出窗口弹出,显示在网页上绘制的填充为绿色的矩形。
广告