js实现svg
SVG 基础概念
SVG(Scalable Vector Graphics)是一种基于 XML 的矢量图形格式,可直接嵌入 HTML 或通过 JavaScript 动态操作。其优势在于缩放不失真,适合图标、图表等场景。
在 HTML 中嵌入 SVG
直接内联 SVG 到 HTML 中,可通过 DOM 操作修改属性或结构:
<svg id="mySvg" width="200" height="200">
<circle cx="50" cy="50" r="40" fill="red" />
</svg>
通过 JavaScript 创建 SVG
使用 document.createElementNS 创建 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", "50");
circle.setAttribute("cy", "50");
circle.setAttribute("r", "40");
circle.setAttribute("fill", "blue");
svg.appendChild(circle);
document.body.appendChild(svg);
动态修改 SVG 属性
通过 JavaScript 直接操作已有 SVG 元素的属性:
const myCircle = document.querySelector("#mySvg circle");
myCircle.setAttribute("fill", "green"); // 修改颜色
myCircle.setAttribute("r", "30"); // 修改半径
实现动画效果
使用 requestAnimationFrame 或 CSS 动画实现 SVG 动态效果:

let angle = 0;
function animate() {
angle += 0.02;
const x = 50 + Math.cos(angle) * 30;
const y = 50 + Math.sin(angle) * 30;
myCircle.setAttribute("cx", x);
myCircle.setAttribute("cy", y);
requestAnimationFrame(animate);
}
animate();
事件交互
为 SVG 元素添加事件监听器实现交互:
myCircle.addEventListener("click", () => {
myCircle.setAttribute("fill", "purple");
});
使用第三方库
若需复杂功能,可借助库如 Snap.svg 或 D3.js:
// 使用 D3.js 示例
d3.select("#mySvg circle")
.transition()
.duration(1000)
.attr("r", 50);
注意事项
- SVG 元素必须使用
createElementNS而非createElement。 - 坐标系统以左上角为原点
(0, 0),X 轴向右,Y 轴向下。 - 路径(
<path>)通过d属性定义,支持复杂图形绘制。






