SVG 模式
SVG 模式 - <pattern>
<pattern>
元素用于创建图形,该图形会在重复的 x 和 y 坐标间隔处重新绘制,以覆盖某个区域。
所有 SVG 模式都定义在 <defs>
元素内。<defs>
元素是“定义”的缩写,其中包含特殊元素(例如模式)的定义。
<pattern>
元素有一个必需的 id
属性,用于标识该模式。图形/图像然后指向要使用的模式。
然后,在 <pattern>
元素内部,我们放入一个或多个将用作填充模式的元素。
一个简单的模式示例
以下示例创建一个用小圆填充的矩形
这是 SVG 代码
示例
<svg width="400" height="110" xmlns="http://www.w3.org/2000/svg">
<defs>
<pattern id="patt1" x="0" y="0" width="20" height="20" patternUnits="userSpaceOnUse">
<circle cx="10" cy="10" r="10" fill="red" />
</pattern>
</defs>
<rect width="200" height="100" x="0" y="0" stroke="black" fill="url(#patt1)" />
</svg>
自己动手试一试 »
代码解释
<pattern>
元素的id
属性为模式定义了一个唯一的名称<pattern>
元素的x
和y
属性定义了模式在形状内开始的距离<pattern>
元素的width
和height
属性定义了模式的宽度和高度<pattern>
元素内的<circle>
元素定义了填充模式的形状<rect>
元素的fill="url(#patt1)"
属性指向“patt1”模式- 矩形将被填充模式填充
带渐变的模式
以下示例创建一个用浅蓝色小矩形和渐变圆填充的矩形
这是 SVG 代码
示例
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
<defs>
<linearGradient id="grad1">
<stop offset="0%" stop-color="white" />
<stop offset="100%" stop-color="red" />
</linearGradient>
<pattern id="patt2" x="0" y="0" width="0.25" height="0.25">
<rect x="0" y="0" width="50" height="50" fill="lightblue" />
<circle cx="25" cy="25" r="20" fill="url(#grad1)" fill-opacity="0.8" />
</pattern>
</defs>
<rect width="200" height="200" x="0" y="0" stroke="black" fill="url(#patt2)" />
</svg>
自己动手试一试 »
代码解释
<pattern>
元素的id
属性为模式定义了一个唯一的名称<pattern>
元素的x
和y
属性定义了模式在形状内开始的距离<pattern>
元素的width
和height
属性定义了模式的宽度和高度。我们希望模式在水平方向重复 4 次,在垂直方向重复 4 次,因此我们将高度和宽度设置为 0.25(表示模式的宽度和高度是整个框大小的 25%)<pattern>
元素内的<rect>
元素定义了填充模式的一种形状(一个浅蓝色的 50x50 矩形)<pattern>
元素内的<circle>
元素定义了填充模式的另一种形状(一个从白色到红色的渐变圆)<circle>
元素的fill="url(#grad1)"
属性指向“grad1”渐变<rect>
元素的fill="url(#patt2)"
属性指向“patt2”模式- 矩形将被填充模式填充