JF-Mechs
JF-Mechs

Reputation: 1081

How to fill quadratic curve in canvas?

Is it possible to fill quadratic curve?

I am newbie in canvas and I'd like to fill the color of the upper part of what I have drawn in context.quadraticCurveTo(), but when I tried the context.fill() it does not fill my expected section. I'd like to fill in the upper part of the canvas which was separated by the stroke.

See attached snippet.

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>

Upvotes: 0

Views: 1939

Answers (1)

helb
helb

Reputation: 3234

The easiest way is probably just drawing some lines along the canvas edge to make a closed shape:

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>

Upvotes: 5

Related Questions