图像与嵌入
SVG 支持嵌入外部图像和其他内容,包括位图图像和 HTML 内容。
image 元素
<image> 元素用于在 SVG 中嵌入外部图像。
基本语法
xml
<image x="x坐标" y="y坐标" width="宽度" height="高度" href="图像URL"/>示例
html
<svg width="400" height="300">
<!-- 嵌入 PNG 图像 -->
<image x="50" y="50" width="100" height="100" href="image.png"/>
<!-- 嵌入 SVG 图像 -->
<image x="200" y="50" width="100" height="100" href="image.svg"/>
</svg>图像属性
| 属性 | 描述 | 取值 |
|---|---|---|
x | 图像左上角 x 坐标 | 数值 |
y | 图像左上角 y 坐标 | 数值 |
width | 图像宽度 | 数值 |
height | 图像高度 | 数值 |
href | 图像 URL | URL 字符串 |
preserveAspectRatio | 图像缩放方式 | 与 viewBox 相同 |
图像裁剪
html
<svg width="200" height="200">
<defs>
<clipPath id="circleClip">
<circle cx="100" cy="100" r="50"/>
</clipPath>
</defs>
<image x="50" y="50" width="100" height="100"
href="image.jpg" clip-path="url(#circleClip)"/>
</svg>foreignObject 元素
<foreignObject> 元素允许在 SVG 中嵌入外部 XML 内容,包括 HTML。
基本语法
xml
<foreignObject x="x坐标" y="y坐标" width="宽度" height="高度">
<!-- 外部内容 -->
</foreignObject>示例
html
<svg width="400" height="300">
<foreignObject x="50" y="50" width="300" height="200">
<body xmlns="http://www.w3.org/1999/xhtml">
<div style="background: yellow; padding: 10px;">
<h1>HTML in SVG</h1>
<p>这是嵌入在 SVG 中的 HTML 内容</p>
</div>
</body>
</foreignObject>
</svg>嵌入 HTML
嵌入表单
html
<svg width="400" height="300">
<foreignObject x="50" y="50" width="300" height="200">
<body xmlns="http://www.w3.org/1999/xhtml">
<form>
<label>用户名:</label>
<input type="text"/><br/><br/>
<label>密码:</label>
<input type="password"/><br/><br/>
<button type="submit">登录</button>
</form>
</body>
</foreignObject>
</svg>嵌入视频
html
<svg width="600" height="400">
<foreignObject x="50" y="50" width="500" height="300">
<body xmlns="http://www.w3.org/1999/xhtml">
<video width="500" height="300" controls>
<source src="video.mp4" type="video/mp4"/>
</video>
</body>
</foreignObject>
</svg>实际应用
图片画廊
html
<svg width="600" height="400">
<image x="0" y="0" width="200" height="200" href="photo1.jpg"/>
<image x="200" y="0" width="200" height="200" href="photo2.jpg"/>
<image x="400" y="0" width="200" height="200" href="photo3.jpg"/>
<image x="100" y="200" width="200" height="200" href="photo4.jpg"/>
<image x="300" y="200" width="200" height="200" href="photo5.jpg"/>
</svg>响应式图片
html
<svg width="100%" viewBox="0 0 400 300">
<image x="0" y="0" width="400" height="300" href="responsive.jpg"/>
</svg>注意事项
- 跨域限制: 从外部域加载图像可能受到 CORS 限制
- foreignObject 兼容性: 并非所有浏览器都完全支持 foreignObject
- 安全性: 某些浏览器可能会限制 foreignObject 中的交互功能
- 性能: 大量图像嵌入可能影响性能