画布 - 填充线条下方或上方的区域

Bin*_*nev 6 html javascript charts canvas

好的,我有一个很难解决的问题。我有一个 HTML5 画布,我在其中绘制了两个图表(线)。我有每个图表的线连接点,我有两个 y 值(图片中的 X,Y),我必须在其中画一条线并填充图表的上方或下方。我真的似乎无法让它工作,因为我尝试为特定图表上方的所有内容着色并用矩形剪裁它,但我有两个图表,所以我必须有两个剪裁区域,这提供了不正确的解决方案。

帖子里有图片可以看案例

在此处输入图片说明

所以我有一个红色图表和一个棕色图表以及 X 和 Y 的值(这是彩色线条)。X 是浅蓝色 - 我要为下面的图表着色的高度。Y 是浅灰色,是棕色图表上方着色的高度。

如何在不知道图表与 X 或 Y 的交叉点的情况下实现这一点?

我正在使用的代码是这样的。我为每个图表调用两次。我省略了绘制图表的代码——它是使用“点”数组绘制的。不幸的是,我没有颜色区域末端和图表之间的交叉点(红色和浅蓝色的交叉;棕色和浅灰色)

ctx.rect(clipX, clipY, clipWidth, clipHeight);
		ctx.stroke();
		ctx.clip();

		//fill the area of the chart above or below
		ctx.globalAlpha = 0.4;
		ctx.strokeStyle = color;
		ctx.fillStyle = color;
		ctx.beginPath();
		ctx.moveTo(points[0].x, points[0].y + visibleGraphicSpace);
		for (var i = 1; i < points.length; i++) {
			ctx.lineTo(points[i].x, points[i].y + visibleGraphicSpace);
		}
		ctx.closePath();
		ctx.fill();
Run Code Online (Sandbox Code Playgroud)

首先,我为可见区域绘制矩形,然后使用给定的点数组绘制图表,关闭它并填充上方或下方的所有内容,直到画布结束。但是这个解决方案只需要第二个填充权,因为它覆盖了第一个。

PS:我需要绘制两种着色填充物,而不仅仅是其中一种。

我希望我能很好地解释它。如果您有任何问题,请不要介意提问。提前感谢您的帮助。

mar*_*rkE 5

您可以创建剪切区域(使用context.clip)以确保蓝色和灰色填充包含在图表创建的路径内。设置剪切区域后,任何新绘图都不会显示在剪切区域之外。

  • 将一些图表点保存在数组中。
  • 将填充的顶部和底部范围保存在图表点内
  • 定义图表路径(==绘制点而不描边点)
  • 从路径创建剪切区域(所有新绘图将包含在剪切区域内,不会出现在该区域之外)
  • 填充剪切区域(用蓝色和灰色填充)
  • 抚摸路径(用红色和栗色的笔触)

注意:当您创建剪切路径时,只能通过将剪切代码包裹在context.save&内来“取消剪切”它context.restore

在此输入图像描述

下面是带注释的代码和演示:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

var pts0=[
  {x:119,y:239},
  {x:279,y:89},
  {x:519,y:249},
  {x:739,y:83},
  {x:795,y:163},
];
  var fill0={top:75,bottom:133};

  var pts1=[
  {x:107,y:342},
  {x:309,y:523},
  {x:439,y:455},
  {x:727,y:537},
  {x:757,y:389}
];
var fill1={top:473,bottom:547};

filledChart(pts0,fill0,'red','skyblue');
filledChart(pts1,fill1,'maroon','lightgray');


function filledChart(pts,fill,strokecolor,fillcolor){
  // define the path
  // This doesn't stroke the path, it just "initializes" it for use
  ctx.beginPath();
  ctx.moveTo(pts[0].x,pts[0].y);
  for(var i=0;i<pts.length;i++){
    var pt=pts[i];
    ctx.lineTo(pt.x,pt.y);
  }

  // save the un-clipped context state
  ctx.save();

  // Create a clipping area from the path
  // All new drawing will be contained inside
  // the clipping area
  ctx.clip();

  // fill some of the clipping area
  ctx.fillStyle=fillcolor;
  ctx.fillRect(0,fill.top,cw,fill.bottom-fill.top);

  // restore the un-clipped context state
  // (the clip is un-done)
  ctx.restore();

  // stroke the path
  ctx.strokeStyle=strokecolor;
  ctx.lineWidth=2;
  ctx.stroke();
}
Run Code Online (Sandbox Code Playgroud)
body{ background-color: ivory; }
#canvas{border:1px solid red; }
Run Code Online (Sandbox Code Playgroud)
<canvas id="canvas" width=800 height=550></canvas>
Run Code Online (Sandbox Code Playgroud)