如何在画布上填充二次曲线?

时间:2018-12-27 11:21:22

标签: javascript html css canvas html5-canvas

是否可以填充二次曲线?

我是画布上的新手,我想填充我在context.quadraticCurveTo()中绘制的内容的上部,但是当我尝试context.fill()时,它并不能填充我期望的部分。我想填写被笔触分开的画布的上半部分。

请参见附件片段。

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

// Quadratic Bézier curve
ctx.beginPath();
ctx.moveTo(0, 60);
ctx.quadraticCurveTo(ch, 0, cw, 35);
ctx.stroke();
ctx.fill();
#canvas {
  border: 1px solid;
}
<canvas id="canvas"></canvas>

1 个答案:

答案 0 :(得分:4)

最简单的方法可能是沿着画布边缘绘制一些线条以形成闭合形状:

enter image description here

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

// Quadratic Bézier curve
ctx.beginPath();
ctx.moveTo(0, 60);
ctx.quadraticCurveTo(ch, 0, cw, 35);
ctx.lineTo(cw, 0);   // these two lines
ctx.lineTo(0, 0);    // are new
                     // you can even add a third one that goes from 0,0
                     // to 0,60 … but .fill() closes the shape even without it
ctx.stroke();
ctx.fill();
#canvas {
  border: 1px solid;
}
<canvas id="canvas"></canvas>