[英]HTML Canvas: How to color area under a line graph?
我正在尝试创建山形图(折线图和下面的区域被阴影化),但是,无论我如何尝试,阴影区域都不能覆盖整个区域。 因为我的图表是一条开放路径,所以填写的结果是通过图表线的区域。
下面是我放在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>
您只需要先stroke()
您的路径,然后是lineTo(lastX, canvasHeight); lineTo(firstX, canvasHeight);
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; }
<canvas id="canvas"></canvas>
就像是:
//<![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(); }); //]]>
/* external.css */ html,body{ padding:0; margin:0; } .main{ width:940px; padding:20px; margin:0 auto; } #graph{ width:300px; height:150px; }
<!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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.