作者:尘世聚散 | 来源:互联网 | 2023-01-17 14:49
1> Kaiido..:
您只需先走stroke()
自己的路,然后lineTo(lastX, canvasHeight); lineTo(firstX, canvasHeight);
再打电话fill()
。
这样,您的填充区域将始终覆盖所有底部区域。
如果您只想填充最大Y值,而不是画布底部,则可以从各点(此代码段中的注释部分)获取此maxY:
const width = canvas.width;
const height = canvas.height;
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'red';
function plotPoints() {
const pts = generatePoints(32);
// first plot the stroke
pts.forEach((pt) => ctx.lineTo(pt.x, pt.y));
ctx.stroke();
// now define the bottom of the filled area
const maxY = height; //Math.max.apply(null, pts.map(pt=>pt.y));
// draw the missing parts
ctx.lineTo(pts[pts.length - 1].x, maxY); // bottom-right
ctx.lineTo(pts[0].x, maxY); // bottom-left
ctx.globalCompositeOperation = "destination-over"; // draw behind
ctx.fill(); // will close the path for us
ctx.globalCompositeOperation = "source-over"; // normal behavior
}
plotPoints();
function generatePoints(nbOfPoints) {
const pts = [];
for (let i = 0; i <= nbOfPoints; i++) {
pts.push({
x: i * (width / nbOfPoints),
y: Math.random() * height
});
}
return pts;
}
canvas {
border: 1px solid lightgray;
}