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

时间:2017-09-21 03:28:54

标签: javascript html5 canvas charts html5-canvas

我正在尝试创建一个山图(折线图和下面的区域是阴影)但是,无论我尝试什么,阴影区域都不会覆盖整个区域。因为我的图表是一个开放路径,所以填充会产生通过图表线的区域。

enter image description here

以下是我在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();

<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:5)

您必须先stroke()路径,然后lineTo(lastX, canvasHeight); lineTo(firstX, canvasHeight);才能致电fill()

这样,您填充的区域将始终覆盖所有底部区域 如果您只想填充最大Y值,而不是填充到画布底部,那么您可以从您的点获取此最大值(下面代码段中的注释部分):

&#13;
&#13;
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.fill(); // will close the path for us
}
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;
}
&#13;
canvas {
  border: 1px solid lightgray;
}
&#13;
<canvas id="canvas"></canvas>
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

就像:

&#13;
&#13;
//<![CDATA[
/* external.js */
var doc, bod, E; // for use on other loads
addEventListener('load', function(){
doc = document, bod = doc.body;
E = function(id){
  return doc.getElementById(id);
}
var graph = E('graph'), ctx = graph.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.lineTo(300,110); ctx.lineTo(300,150);
ctx.fillStyle = 'red'; ctx.fill(); ctx.stroke();
});
//]]>
&#13;
/* external.css */
html,body{
  padding:0; margin:0;
}
.main{
  width:940px; padding:20px; margin:0 auto;
}
#graph{
  width:300px; height:150px;
}
&#13;
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
  <head>
    <meta http-equiv='content-type' content='text/html;charset=utf-8' />
    <meta name='viewport' content='width=device-width' />
    <title>Graph</title>
    <link type='text/css' rel='stylesheet' href='css/external.css' />
    <script type='text/javascript' src='external.js'></script>
  </head>
  <body>
    <div class='main'>
      <canvas id='graph'></canvas>
    </div>
  </body>
</html>
&#13;
&#13;
&#13;