Write text on canvas with background

42,817

Solution 1

I simpler solution is to call fillText twice. First a string of Unicode+2588 █ which is a black rectangle repeated the same length as the text using the background color. And then call fillText as normal with the foreground color.

Solution 2

This function gives you vertically and horizontally centered text with a background. It only works well with monospaced fonts (characters with the same width). The function counts the number of character in the string you which to print and multiplies them with 0.62 (assuming that the width of the font is slightly less than 0.62 times the height). The background is 1.5 times bigger than the font size. Change this to fit your needs.

function centeredText(string, fontSize, color) {
        var i = string.length;
        i = i*fontSize*0.62;
        if (i > canvas.width) {
          i = canvas.width;
        }
        ctx.fillStyle = "RGBA(255, 255, 255, 0.8)";
        ctx.fillRect(canvas.width / 2 - i / 2,canvas.height / 2 - (fontSize * 1.5) / 2, i, (fontSize * 1.5) );
        ctx.font = fontSize.toString() + "px monospace";
        ctx.fillStyle = color;
        ctx.textBaseline = "middle";
        ctx.textAlign = "center";

        ctx.fillText(string, canvas.width / 2, canvas.height / 2);
    }

So calling the function would look something like this.

centeredText("Hello World", 30, "red");
Share:
42,817
rask
Author by

rask

Updated on May 03, 2020

Comments

  • rask
    rask about 4 years

    Is it possible to write image on canvas and write text with background? For example like this:

    http://awesomescreenshot.com/09f1qf2213