Home > Blockchain >  ctx.fillText isn't doing anything
ctx.fillText isn't doing anything

Time:02-03

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
    );
}

CodePudding user response:

You might want to double check the return of measureText:
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/measureText#return_value
there is nothing height related there...

If we remove those textWidth & textHeight your drawSelectionRect function works.

I believe what you are trying to accomplish is to align the text, perhaps with these, you can do it:

Here is your code with those

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>

Remember console.log( is your friend, when you are not sure what is going on, output the variables you are using and see what is not the way you plan it

  •  Tags:  
  • Related