当前位置:首页 > JavaScript

js实现曲线

2026-01-31 21:23:05JavaScript

使用Canvas绘制曲线

在JavaScript中,Canvas API提供了多种绘制曲线的方法。beginPath()开始路径,moveTo()移动到起点,quadraticCurveTo()bezierCurveTo()绘制曲线。

const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

ctx.beginPath();
ctx.moveTo(50, 50);
ctx.quadraticCurveTo(100, 100, 150, 50); // 二次贝塞尔曲线
ctx.stroke();

使用SVG创建曲线

SVG的<path>元素可通过d属性定义曲线路径。M移动到起点,QC分别创建二次或三次贝塞尔曲线。

<svg width="200" height="200">
  <path d="M50 50 Q100 100 150 50" stroke="black" fill="none"/>
</svg>

使用数学函数生成曲线点

通过数学函数(如正弦函数)生成坐标点,再用线段连接形成曲线。

const points = [];
for (let x = 0; x < 200; x++) {
  const y = 50 + 30 * Math.sin(x * 0.05);
  points.push({x, y});
}

ctx.beginPath();
points.forEach((point, i) => {
  if (i === 0) ctx.moveTo(point.x, point.y);
  else ctx.lineTo(point.x, point.y);
});
ctx.stroke();

使用第三方库(如D3.js)

D3.js提供高级曲线生成功能,如插值曲线或平滑过渡。

import * as d3 from 'd3';

const lineGenerator = d3.line()
  .x(d => d.x)
  .y(d => d.y)
  .curve(d3.curveBasis);

const pathData = lineGenerator(points);

曲线动画效果

结合requestAnimationFrame动态更新曲线坐标,实现动画效果。

let offset = 0;
function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.beginPath();
  for (let x = 0; x < 200; x++) {
    const y = 50 + 30 * Math.sin(x * 0.05 + offset);
    if (x === 0) ctx.moveTo(x, y);
    else ctx.lineTo(x, y);
  }
  ctx.stroke();
  offset += 0.1;
  requestAnimationFrame(animate);
}
animate();

js实现曲线

标签: 曲线js
分享给朋友:

相关文章

jquery.js

jquery.js

jQuery 简介 jQuery 是一个快速、简洁的 JavaScript 库,用于简化 HTML 文档遍历、事件处理、动画设计和 Ajax 交互。它的设计宗旨是“Write Less, Do Mor…

css3结合js制作

css3结合js制作

CSS3 结合 JavaScript 制作动态效果 CSS3 和 JavaScript 结合可以实现丰富的动态效果,包括动画、交互和响应式设计。以下是几种常见的实现方式: CSS3 动画与 Jav…

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 实现页面跳转,这是最常用的方法。 window.location.href = 'https://…

js实现拖拽

js实现拖拽

实现拖拽的基本步骤 通过监听鼠标事件(mousedown、mousemove、mouseup)实现拖拽功能。以下是核心代码逻辑: const draggableElement = document.…

js实现倒计时

js实现倒计时

使用 setInterval 实现倒计时 通过 setInterval 定时器每秒更新剩余时间,适用于简单倒计时场景。 function countdown(seconds, callback)…

js实现图片上传

js实现图片上传

图片上传的基本实现 使用HTML的<input type="file">元素配合JavaScript的File API可以实现图片上传功能。HTML部分需要创建一个文件选择输入框和一个用于…