HTML Canvas:如何为折线图下的区域着色?

Typ*_*ter 0 javascript charts html5 canvas html5-canvas

我正在尝试创建山形图(折线图和下面的区域被阴影化),但是,无论我如何尝试,阴影区域都不能覆盖整个区域。因为我的图表是一条开放路径,所以填写的结果是通过图表线的区域。

在此处输入图片说明

下面是我放在W3School上以演示该问题的示例代码。

我还在同一行上看到了其他一些问题,但是也遵循这些问题也会导致同样的问题。

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.moveTo(0,150);
ctx.lineTo(100,70);
ctx.lineTo(150,100);
ctx.lineTo(200,140);
ctx.lineTo(250,90);
ctx.lineTo(300,110);
ctx.fillStyle ="red";
ctx.fill();
ctx.stroke();
Run Code Online (Sandbox Code Playgroud)
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
Run Code Online (Sandbox Code Playgroud)

Kai*_*ido 5

您只需先走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;
}
Run Code Online (Sandbox Code Playgroud)
canvas {
  border: 1px solid lightgray;
}
Run Code Online (Sandbox Code Playgroud)
<canvas id="canvas"></canvas>
Run Code Online (Sandbox Code Playgroud)