js实现曲线
使用Canvas绘制曲线
在JavaScript中,Canvas API提供多种方法绘制曲线。beginPath()开始路径,moveTo(x, y)设置起点,quadraticCurveTo(cp1x, cp1y, x, y)绘制二次贝塞尔曲线,bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)绘制三次贝塞尔曲线。
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(50, 50);
ctx.quadraticCurveTo(100, 25, 150, 50);
ctx.stroke();
使用SVG绘制曲线
SVG的<path>元素通过d属性定义路径。M移动至起点,Q创建二次贝塞尔曲线,C创建三次贝塞尔曲线。
<svg width="200" height="100">
<path d="M50,50 Q100,25 150,50" stroke="black" fill="none"/>
</svg>
使用数学函数生成曲线
通过数学函数生成曲线点,如正弦函数,再用lineTo()连接。
const canvas = document.getElementById('mathCanvas');
const ctx = canvas.getContext('2d');
ctx.beginPath();
for (let x = 0; x < 200; x++) {
const y = 50 + 20 * Math.sin(x * 0.1);
ctx.lineTo(x, y);
}
ctx.stroke();
使用第三方库绘制曲线
库如D3.js或Chart.js简化曲线绘制。D3.js示例:
import * as d3 from 'd3';
const line = d3.line()
.x(d => d.x)
.y(d => 50 + 20 * Math.sin(d.x * 0.1));
const data = Array.from({length: 200}, (_, i) => ({x: i}));
d3.select('svg')
.append('path')
.attr('d', line(data))
.attr('stroke', 'black')
.attr('fill', 'none');
曲线动画效果
结合requestAnimationFrame实现动画,动态更新曲线控制点或路径。

let angle = 0;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.moveTo(50, 50);
const cp1y = 25 + 10 * Math.sin(angle);
ctx.quadraticCurveTo(100, cp1y, 150, 50);
ctx.stroke();
angle += 0.05;
requestAnimationFrame(animate);
}
animate();






