简体   繁体   English

填充 html5 画布上两条贝塞尔曲线下的区域

[英]Filling area under two bezier curves on html5 canvas

This is my first time using html canvas, and I am a little stumped with this one.这是我第一次使用 html canvas,我对这个有点难。 I am trying to build an image like this on an html canvas:我正在尝试在 html 画布上构建这样的图像:

Html canvas html画布

在此处输入图片说明

This is what I have tried so far, and I can't seem to fill the areas beneath the lines with the appropriate color.这是我到目前为止所尝试的,我似乎无法用适当的颜色填充线条下方的区域。 in particular, I tried context.fill();特别是,我尝试了context.fill(); . .

Here is a stackblitz of the working example that I have, minus the fills beneath the lines.这是我拥有的工作示例的堆栈闪电战,减去线条下方的填充。

https://stackblitz.com/edit/js-troahu?file=index.js https://stackblitz.com/edit/js-troahu?file=index.js

To be able to fill something on the canvas you actually need to define that area completely .为了能够在画布上填充某些内容,您实际上需要完全定义该区域。 If you just mimic the look of the curves, you have an open path only and it merely fills the 'area' that lies in-between the start & end point.如果您只是模仿曲线的外观,那么您只有一条开放路径,它只会填充起点和终点之间的“区域”。

The fix is simple though - just add two more straight lines [C, D] that make up the rectangular shape below the curve and you're good to go.修复很简单 - 只需添加两条直线 [C, D] 来构成曲线下方的矩形形状,您就可以开始了。

Here's a working example based on your stackblitz code (just click on 'Run code snippet'):这是一个基于您的 stackblitz 代码的工作示例(只需单击“运行代码片段”):

 var canvas = document.querySelector("canvas"); var context = canvas.getContext("2d"); function drawCurve(x, y, curves, canvasColor, strokeStyle) { context.beginPath(); context.moveTo(x, y); for (let i = 0; i < curves.length; i++) { let c = curves[i]; context.quadraticCurveTo(c[0], c[1], c[2], c[3]); } context.lineTo(canvas.width, canvas.height); context.lineTo(0, canvas.height); context.fillStyle = canvasColor; context.fill(); } drawCurve( 0, 45, [ [75, 27, 173, 44], [240, 50, 300, 35] ], "#98dbcc" ); drawCurve( 0, 35, [ [65, 65, 125, 45], [197, 20, 300, 45] ], "#00a780" );
 <div class="canvas-container"> <canvas id="canvas"></canvas> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM