SVG rect元素
SVG <rect>元素代表一个矩形。使用此元素,我们可以绘制具有各种宽度,高度,不同笔触(轮廓)和填充颜色,尖角或者圆角等的矩形。这说明了SVGrect元素。
如果我们更喜欢将此SVGrect教程作为视频观看,我在YouTube上有一个视频版本:
一个rect例子
这是一个简单的<rect>示例:
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<rect x="10" y="10" height="100" width="100"
style="stroke:#006600; fill: #00cc00"/>
</svg>
矩形的位置由" x"和" y"属性确定。请记住,此位置是相对于任何封闭的(父)元素位置而言的。
矩形的大小由" width"和" height"属性确定。
" style"属性允许我们设置其他样式信息,例如笔触和填充颜色,笔触的宽度等。这将在其他文本中更详细地介绍。
这是生成的矩形图像:
圆角
可以在矩形上绘制圆角。属性rx和ry决定拐角处的圆角。 rx属性决定了四舍五入的宽度,而ry属性决定了四舍五入的高度。这是三个矩形,其中的rx和ry分别设置为5、10和15. 注意四舍五入中的不同大小。
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<rect x="10" y="10" height="50" width="50"
rx="5" ry="5"
style="stroke:#006600; fill: #00cc00"/>
<rect x="70" y="10" height="50" width="50"
rx="10" ry="10"
style="stroke:#006600; fill: #00cc00"/>
<rect x="130" y="10" height="50" width="50"
rx="15" ry="15"
style="stroke:#006600; fill: #00cc00"/>
</svg>
在这些示例中,每个矩形中的rx和ry设置为相同的值。如果仅设置rx属性,则ry属性的值将与rx相同。这是定义均匀圆角的快捷方式。
这是两个示例,其中rx属性都设置为10,而ry属性设置为5和15. 这将向我们展示在不同的高度和宽度下,圆角矩形的外观。
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<rect x="10" y="10" height="50" width="50"
rx="10" ry="5"
style="stroke:#006600; fill: #00cc00"/>
<rect x="130" y="10" height="50" width="50"
rx="10" ry="15"
style="stroke:#006600; fill: #00cc00"/>
</svg>
矩形笔画
我们可以使用SVG笔触样式属性设置矩形的笔划(轮廓)的样式。本示例将笔触颜色设置为深绿色,并将笔划宽度设置为3:
<rect x="20" y="20" width="100" height="100"
style="stroke: #009900;
stroke-width: 3;
fill: none;
"
/>
这是rect元素在浏览器中呈现时的外观:
我们也可以使用stroke-dasharray样式属性使矩形笔划变为虚线。这是一个例子:
<rect x="20" y="20" width="100" height="100"
style="stroke: #009900;
stroke-width: 3;
stroke-dasharray: 10 5;
fill: none;
"
/>
这是rect元素在浏览器中呈现时的外观:
矩形填充
我们可以使用SVG填充样式属性填充矩形。例如,我们可以通过将样式属性fill设置为none来选择不填充rect元素。这是一个例子:
<rect x="20" y="20" width="100" height="100"
style="stroke: #009900;
fill: none;
"
/>
这是在浏览器中呈现时没有填充的rect元素的外观:
我们也可以选择用颜色填充矩形。这个例子用明亮的绿色填充rect元素:
<rect x="20" y="20" width="100" height="100"
style="stroke: #009900;
fill: #33ff33;
"
/>
这是在浏览器中呈现时rect元素的方式:
我们也可以使用fill-opacity样式属性使填充透明。此示例显示了两个矩形,一个矩形部分在另一个矩形的顶部,而顶部的矩形是半透明的:
<rect x="20" y="20" width="100" height="100"
style="stroke: #009900;
fill: #33ff33;
"
/>
<rect x="50" y="50" width="100" height="100"
style="stroke: #000099;
fill: #3333ff;
fill-opacity: 0.5;
"
/>
这是rect元素在浏览器中呈现时的外观:
在这个例子中,第二个矩形的笔触不是透明的,但是我们可以使用stroke-opacity样式属性使其透明。

