Estoy creando un sitio web donde quiero tener texto escrito en medio de un rectángulo. El texto será un número del 1 al 100. Por alguna razón ctx.fillText() no está haciendo nada. Mi lienzo no es pequeño. Es tan grande como la imagen que se está dibujando en él.
Código:
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 ); }Es posible que desee verificar dos veces el retorno de MeasureText:
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/measureText#return_value
no hay nada relacionado con la altura allí...
Si eliminamos esos textWidth y textHeight, su función drawSelectionRect funciona.
Creo que lo que estás tratando de lograr es alinear el texto, quizás con estos, puedes hacerlo:
Aquí está tu código con esos
const editCanvas = document.getElementById('c'); const ctx = editCanvas.getContext("2d"); 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); console.log(ctx.measureText(text)) ctx.fillStyle = "#000"; ctx.font = "16px sans-serif"; ctx.textBaseline = "middle"; ctx.textAlign = "center"; ctx.fillText( text, x + width / 2, y + height / 2, width ); } drawSelectionRect( "ooo", {x:2, y:2, width:40, height:40}, {strokeWidth:3, lineDash:[0], strokeColor: "black"}, "red" ) <canvas id="c"></canvas> Recuerde console.log( es su amigo, cuando no esté seguro de lo que está pasando, muestre las variables que está usando y vea cuál no es la forma en que lo planea