猿问

canvas绘制圆滑曲线的折线图

用原生JS写折线图,直角的可以写出来,但是目前需要变做圆滑的曲线,类似:

尝试用贝塞尔曲线画

let curveness = 0.2;

// 起点

let x0 = vertices[t - 1].x;

let y0 = vertices[t - 1].y;

// 终点

let x2 = vertices[t].x;

let y2 = vertices[t].y;

// 贝塞尔曲线中间点 curveness曲率

let x1 = (x0 + x2) / 2 - (y0 - y2) * curveness;

let y1 = (y0 + y2) / 2 - (y2 - y0) * curveness;

ctx.beginPath();

ctx.moveTo(vertices[t - 1].x, vertices[t - 1].y);

ctx.bezierCurveTo(x0, y0, x1, y1, x2, y2);

// ctx.arcTo(x1, y1, x2, y2, 100);

效果达不到需求的样子

https://img3.mukewang.com/5c96ebec000157d804580154.jpg

拐点处还是直角的,有没有大神可以提供下解决思路呢


慕斯709654
浏览 988回答 1
1回答

函数式编程

三次曲线还没研究过,如果是二次曲线可以先求两点之间的中点,让曲线的终点是这个中点即可,当然如果要经过首尾的点的话,就要排除一下。核心代码如下:随机点连线例子context.beginPath();context.moveTo(points[0].x, points[0].y);for (i = 1; i < numPoints - 2; i++) {&nbsp; ctrlPoint.x = (points[i].x + points[i + 1].x) / 2;&nbsp; ctrlPoint.y = (points[i].y + points[i + 1].y) / 2;&nbsp; context.quadraticCurveTo(points[i].x, points[i].y, ctrlPoint.x, ctrlPoint.y);}context.quadraticCurveTo(points[i].x, points[i].y, points[i + 1].x, points[i + 1].y);context.stroke();
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答