js实现svg
SVG 基础概念
SVG(Scalable Vector Graphics)是一种基于 XML 的矢量图形格式,可直接嵌入 HTML 或通过 JavaScript 动态操作。
在 HTML 中嵌入 SVG
直接通过 <svg> 标签嵌入静态 SVG 内容:
<svg width="200" height="200">
<circle cx="100" cy="100" r="50" fill="red" />
</svg>
使用 JavaScript 动态创建 SVG
通过 DOM API 动态生成 SVG 元素并添加到页面:

const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("width", "200");
svg.setAttribute("height", "200");
const circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
circle.setAttribute("cx", "100");
circle.setAttribute("cy", "100");
circle.setAttribute("r", "50");
circle.setAttribute("fill", "blue");
svg.appendChild(circle);
document.body.appendChild(svg);
操作 SVG 属性
通过 JavaScript 修改已有 SVG 元素的属性:
const circle = document.querySelector("circle");
circle.setAttribute("fill", "green"); // 修改填充颜色
circle.setAttribute("r", "30"); // 修改半径
事件监听
为 SVG 元素添加交互事件(如点击、悬停):

const circle = document.querySelector("circle");
circle.addEventListener("click", () => {
circle.setAttribute("fill", "purple");
});
动画实现
通过 CSS 或 JavaScript 实现 SVG 动画:
CSS 动画示例
circle {
transition: fill 0.3s ease;
}
circle:hover {
fill: orange;
}
JavaScript 动画示例
使用 requestAnimationFrame 实现动态效果:
let angle = 0;
function animate() {
const circle = document.querySelector("circle");
const x = 100 + 50 * Math.cos(angle);
const y = 100 + 50 * Math.sin(angle);
circle.setAttribute("cx", x);
circle.setAttribute("cy", y);
angle += 0.05;
requestAnimationFrame(animate);
}
animate();
使用第三方库
简化复杂操作可使用库如 Snap.svg 或 D3.js:
D3.js 示例
d3.select("body")
.append("svg")
.attr("width", 200)
.attr("height", 200)
.append("circle")
.attr("cx", 100)
.attr("cy", 100)
.attr("r", 50)
.attr("fill", "teal");
注意事项
- 创建 SVG 元素需使用
document.createElementNS并指定命名空间http://www.w3.org/2000/svg。 - SVG 属性(如
cx、fill)需通过setAttribute修改,而非直接赋值。 - 动态生成的 SVG 需确保插入到 DOM 中可见。






