当前位置:首页 > JavaScript

js实现svg

2026-04-07 03:18:16JavaScript

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.svgD3.js
D3.js 示例

js实现svg

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 属性(如 cxfill)需通过 setAttribute 修改,而非直接赋值。
  • 动态生成的 SVG 需确保插入到 DOM 中可见。

标签: jssvg
分享给朋友:

相关文章

js实现日历

js实现日历

实现日历的基本思路 使用JavaScript实现日历的核心是动态生成日期表格,并处理月份切换逻辑。需要计算当前月的天数、起始星期几,并动态渲染到页面上。 获取当前日期信息 通过Date对象获取当前年…

js图片上传实现

js图片上传实现

图片上传的基本实现 使用HTML的<input type="file">元素配合JavaScript的File API实现基础图片上传功能。HTML部分需要设置accept="image/…

js分页实现

js分页实现

分页的基本原理 分页的核心是通过计算当前页码和数据偏移量,从服务器或本地数据中截取对应范围的数据进行展示。通常需要以下参数:当前页码(currentPage)、每页条数(pageSize)、总数据量(…

js实现删除

js实现删除

使用 splice 方法删除数组元素 splice 方法可以删除数组中的元素,并返回被删除的元素。它接受两个参数:起始索引和要删除的元素数量。 const array = [1, 2, 3, 4…

js实现排序

js实现排序

数组排序方法 JavaScript提供了内置的sort()方法用于数组排序。默认情况下,sort()将元素转换为字符串并按照Unicode码点排序。对于数字排序,需传入比较函数。 const num…

js 实现图片轮播

js 实现图片轮播

基础实现方案 使用HTML、CSS和JavaScript创建一个简单的图片轮播。HTML部分定义轮播容器和图片,CSS负责样式布局,JavaScript处理轮播逻辑。 <div class="…