I want to add a text to the center of quadratic curve or line like this:
I tried to add a text with ctx.fillText
but it overlaps the curve.
how can I draw a curve where the curve does not go over the text?
My code:
// draw the curve
const startPoints = this._getStartPoints(); // returns start points [x, y]
const endPoints = this._getEndPoints(); // returns end points [x, y]
ctx.moveTo(...startPoints);
ctx.quadraticCurveTo(...this.getControlPoints(), ...endPoints);
ctx.stroke();
// draw the text
const textMeasurement = ctx.measureText('text on curve');
const middlePoints = this._getControlPoints(); // returns the middle point of the curve [x, y]
const textXPoint = middlePoints[0] - textMeasurement.width / 2;
ctx.fillText('text on curve', textXPoint, middlePoints[1]);
Clipping
Use
ctx.clip
to prevent drawing on parts of the canvas.In this case you want to draw only outside a bounding area. To do this create two clipping rectangle. The first bounding the whole canvas, the second bounding the text bounding area.
Then clip using the
"evenodd"
winding (fill) rule.Example code
Example of clipping outside a bounding box using two rectangle as described above.