Search code examples
javascriptcanvastext

Canvas text not showing? - JavaScript


I am using the ctx.fillText function to draw text onto my screen and it doesn't seem to be appearing.

overlay("rgb(50, 50, 200)", "This is the beginning screen", 48, "black", "center", centerx, centery)

var overlay = function(colour, text, font, size, fontColour, oreintation, x, y){
    ctx.font = size + "px " + font + " " + fontColour
    ctx.textAlign = oreintation
    ctx.fillStyle = colour
    ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height)
    ctx.fillText(text, x, y)
}

Solution

    • You must define your function var overlay before you call it with `overlay(...);

    • centerx & centery are undefined

    • the font face font is missing from overlay(...)

    • the background fill is the same color as the text fill so the text does not show

    Working demo:

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var cw=canvas.width;
    var ch=canvas.height;
    
    
    var overlay = function(colour, text, font, size, fontColour, oreintation, x, y){
      ctx.font = size + "px " + font + " " + fontColour
      ctx.textAlign = oreintation
      ctx.fillStyle = colour
      ctx.fillStyle='gold';
      ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height)
      ctx.fillStyle=fontColour,
      ctx.fillText(text, x, y)
    }
    
    overlay(
      "rgb(50, 50, 200)", 
      "This is the beginning screen",
      'verdana', 
      48, 
      "black", 
      "center", 
      25,
      50
    );
    body{ background-color: ivory; }
    #canvas{border:1px solid red;}
    <canvas id="canvas" width=300 height=300></canvas>