详细介绍SVG矩形rect元素的绑制方法,包括位置、尺寸、圆角等属性的设置。通过实际案例掌握矩形的各种用法,适合前端开发者学习SVG图形绑制。 矩形是最常用的 SVG 形状。
<rect>元素可以绑制各种矩形,从简单的方块到圆角按钮都能实现。
<rect x="x坐标" y="y坐标" width="宽度" height="高度"/>
width:矩形宽度height:矩形高度x:左上角 x 坐标(默认 0)y:左上角 y 坐标(默认 0)rx:水平圆角半径ry:垂直圆角半径最简单的矩形只需要设置宽高:
<rect width="100" height="60" fill="#3498db"/>
<rect x="120" width="100" height="60" fill="#e74c3c"/>
<rect y="80" width="100" height="60" fill="#2ecc71"/>
<rect x="120" y="80" width="100" height="60" fill="#f39c12"/>
使用 rx 和 ry 属性可以创建圆角矩形:
<rect width="80" height="80" fill="#3498db"/>
<rect width="80" height="80" rx="10" fill="#e74c3c"/>
<rect width="80" height="80" rx="20" fill="#2ecc71"/>
<rect width="80" height="80" rx="40" fill="#f39c12"/>
rx:水平方向的圆角半径ry:垂直方向的圆角半径<rect width="80" height="80" rx="20" ry="10" fill="#3498db"/>
<rect width="80" height="80" rx="10" ry="20" fill="#e74c3c"/>
<rect width="80" height="80" rx="20" ry="20" fill="#2ecc71"/>
rx:ry 自动等于 rxry:rx 自动等于 ry矩形支持所有样式属性:
<rect width="60" height="60" fill="#3498db"/>
<rect width="60" height="60" fill="none" stroke="#e74c3c" stroke-width="3"/>
<rect width="60" height="60" fill="#2ecc71" stroke="#27ae60" stroke-width="3"/>
<rect width="60" height="60" fill="#f39c12" stroke="#e67e22" stroke-width="3" rx="10"/>
<rect width="60" height="60" fill="#9b59b6" opacity="0.5"/>
<rect width="100" height="40" rx="5" fill="#3498db"/>
<rect width="100" height="40" rx="20" fill="#e74c3c"/>
<rect width="100" height="40" rx="5" fill="none" stroke="#2ecc71" stroke-width="2"/>
<rect width="260" height="110" rx="10" fill="white" stroke="#e0e0e0"/>
<rect width="60" height="60" rx="5" fill="#3498db"/>
<rect width="260" height="20" rx="10" fill="#ecf0f1"/>
<rect width="180" height="20" rx="10" fill="#3498db"/>
使用滤镜创建阴影:
<defs>
<filter id="shadow">
<feDropShadow dx="3" dy="3" stdDeviation="3" flood-opacity="0.3"/>
</filter>
</defs>
<rect width="100" height="60" rx="10" fill="#3498db" filter="url(#shadow)"/>
<defs>
<linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color:#3498db"/>
<stop offset="100%" style="stop-color:#e74c3c"/>
</linearGradient>
</defs>
<rect width="260" height="50" rx="25" fill="url(#grad1)"/>
Q: 矩形不显示?
A: 检查以下几点:
width 和 height 是否为正值fill 或 strokeQ: 圆角不生效?
A: 确认 rx 值不超过宽高的一半。
Q: 如何画正方形?
A: 设置相同的 width 和 height:
<rect width="100" height="100"/>
矩形是 SVG 中最基础也最常用的形状。通过 x、y、width、height 控制位置和大小,通过 rx、ry 创建圆角效果。配合填充、描边、滤镜等属性,可以创建丰富的视觉效果。