Write text on canvas with background

后端 未结 3 1020
死守一世寂寞
死守一世寂寞 2021-01-03 20:43

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

\"http://awesomes

3条回答
  •  梦谈多话
    2021-01-03 21:08

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

提交回复
热议问题