JavaScript操作SVG需掌握DOM获取、动态创建、事件绑定与动画。1. 用getElementById或querySelector选中SVG元素,通过setAttribute修改fill、stroke等属性;2. 动态创建时必须使用createElementNS('http://www.w3.org/2000/svg', 'rect')指定命名空间;3. 绑定click、mouseover等事件实现交互;4. 利用requestAnimationFrame逐帧更新cx、cy等属性实现动画,结合CSS transition更流畅;5. 注意属性写法如stroke-width在JS中应写为strokeWidth或用setAttribute设置。
JavaScript 操作 SVG 是实现动态矢量图形的核心方式,尤其适用于数据可视化、交互式图表和动画效果。SVG(Scalable Vector Graphics)基于 XML 描述图形,能无损缩放,结合 JavaScript 可以实现元素的创建、修改、监听和动画控制。
在网页中嵌入 SVG 后,可以通过标准 DOM 方法获取并操作其内部元素:
const circle = document.getElementById('myCircle'); circle.setAttribute('fill', 'red'); circle.style.strokeWidth = '3px';
使用 document.createElementNS() 创建 SVG 元素,注意命名空间为 "http://www.w3.org/2000/svg"。
const svg = document.getElementById('mySvg');
const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
rect.setAttribute('x', 50);
rect.setAttribute('y', 50);
rect.setAttribute('width', 100);
rect.setAttribute('height', 60);
rect.setAttribute('fill', 'blue');
svg.appendChild(rect);
SVG 元素支持鼠标和触摸事件,可实现点击、悬停等交互。
circle.addEventListener('click', function() {
this.setAttribute('fill', this.getAttribute('fill') === 'red' ? 'green' : 'red');
});
可通过 JavaScript 控制属性变化实现动画,也可结合 CSS transition 提升流畅性。
let x = 0;
const animate = () => {
x += 2;
circle.setAttribute('cx', x);
if (x < 200) requestAnimationFrame(animate);
};
animate();
基本上就这些。掌握这些基础方法后,可以结合 D3.js 等库构建复杂可视化项目,但原生 JavaScript 操作 SVG 依然是理解底层机制的关键。不复杂但容易忽略的是命名空间和属性写法,比如 stroke-width 在 JS 中要写成 strokeWidth 或用 setAttribute 才有效。