'ctx.fillText isn't doing anything
I'm making a website where I want to have text written in the middle of a rectangle. The text will be a number from 1 to 100. For some reason ctx.fillText() isn't doing anything. My canvas isn't small. It's as big as the image that's being drawn on it.
Code:
const ctx = editCanvas.getContext("2d");
const backgroundImage = new Image();
backgroundImage.src = "some random path";
backgroundImage.onload = () => {
editCanvas.width = backgroundImage.width;
editCanvas.height = backgroundImage.height;
ctx.drawImage(backgroundImage, 0, 0);
};
function drawSelectionRect(
text,
{ x, y, width, height },
{ strokeWidth, lineDash, strokeColor },
fillColor
) {
ctx.lineWidth = strokeWidth;
ctx.setLineDash(lineDash);
ctx.strokeStyle = strokeColor;
ctx.strokeRect(x, y, width, height);
ctx.fillStyle = fillColor;
ctx.fillRect(x, y, width, height);
const { width: textWidth, height: textHeight } = ctx.measureText(text);
ctx.fillStyle = "#000";
ctx.font = "16px sans-serif";
ctx.fillText(
text,
x + width / 2 - textWidth / 2,
y + height / 2 - textHeight / 2,
width
);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
