const drawDifferentColorLine = (ctx, points) => {
const colors = ["red", "green", "blue", "orange"]; // 设置每一段折线的颜色
ctx.save()
for (let i = 0; i < points.length; i++) {
if (i === points.length - 1) return
ctx.beginPath();
ctx.fillStyle = 'red'
ctx.moveTo(points[i].x, points[i].y);
ctx.strokeStyle = colors[i];
const nextPoint = points[i+1]
ctx.lineTo(nextPoint.x, nextPoint.y);
ctx.stroke();
ctx.fill()
}
ctx.closePath()
ctx.restore()
}
const points = [
{ x: 250, y: 50 },
{ x: 300, y: 150 },
{ x: 400, y: 100 },
{ x: 550, y: 200 },
];
drawDifferentColorLine(canvasCtx, points)
canvas画折线,每一段折线颜色不同
于 2023-12-05 12:40:10 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)