js实现曲线
使用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移动到起点,Q或C分别创建二次或三次贝塞尔曲线。
<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();






