在 JavaScript 中创建 SVG(可缩放矢量图形)可以通过多种方式实现,以下是一些基础概念和相关方法:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SVG Example</title>
</head>
<body>
<svg id="mySvg" width="500" height="500"></svg>
<script>
// 获取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', '100');
rect.setAttribute('fill', 'blue');
// 将矩形添加到SVG中
svg.appendChild(rect);
</script>
</body>
</html>
// 创建SVG元素
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('width', '500');
svg.setAttribute('height', '500');
// 创建一个圆形
const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
circle.setAttribute('cx', '250');
circle.setAttribute('cy', '250');
circle.setAttribute('r', '50');
circle.setAttribute('fill', 'red');
// 将圆形添加到SVG中
svg.appendChild(circle);
// 将SVG添加到文档中
document.body.appendChild(svg);
createElementNS('http://www.w3.org/2000/svg', 'elementName')
。setAttribute
方法直接设置样式。通过以上方法,你可以在JavaScript中动态创建和操作SVG图形,实现丰富的图形和动画效果。
领取专属 10元无门槛券
手把手带您无忧上云