Changing color for fillText() on HTML5 <canvas>

user2193106 picture user2193106 · Apr 1, 2013 · Viewed 48.7k times · Source

I am trying to change the color for each line of my messages on canvas, but no success so far. I have tried creating variable for each one of them, but still no luck. any help would be appreciated.

function initiate(){
    var elem = document.getElementById("canvas");
    canvas = elem.getContext("2d");
    addEventListener("mousemove", animation);

    canvas.shadowColor = "rgba(0, 0, 0, 0.5)";
    canvas.shadowOffsetX = 4;
    canvas.shadowOffsetY = 4;
    canvas.shadowBlur = 5;

    canvas.font = "bold 24px verdana, sans-serif ";
    var welcomeMessage ="Welcome to the store!";
    canvas.textAlign = "start";
    canvas.textBaseline = "bottom";
    canvas.fillText(welcomeMessage, 400, 50);

    canvas.font = "bold 14px verdana, sans-serif";
    var message2 = "Your favorite store for videos games and latest DVDs!"; 
    canvas.textAlign = "start";
    canvas.textBaseline = "bottom";
    canvas.fillText(message2, 400, 100);

    canvas.font = "bold 12px verdana, sans-serif";
    canvas.textAlign = "start";
    canvas.textBaseline = "bottom";
    // Create gradient
    //var gradient=canvas.createLinearGradient(0,0,c.width,0);
    //gradient.addColorStop("0","magenta");
    //gradient.addColorStop("0.5","blue");
    //gradient.addColorStop("1.0","red");
    //canvas.fillStyle = gradient;
    canvas.fillText(" <-- Move your mouse aroud to interact with Macroplay smily!", 400, 250);


}

Answer

Gwennael Buchet picture Gwennael Buchet · Apr 1, 2013

you have to set the color for the text.

Something like this:

canvas.font = "bold 24px verdana, sans-serif ";
var welcomeMessage ="Welcome to the store!";
canvas.textAlign = "start";
canvas.textBaseline = "bottom";
canvas.fillStyle = "#ff0000";  //<======= here
canvas.fillText(welcomeMessage, 400, 50);

canvas.font = "bold 14px verdana, sans-serif";
var message2 = "Your favorite store for videos games and latest DVDs!"; 
canvas.textAlign = "start";
canvas.textBaseline = "bottom";
canvas.fillStyle = "#00ff00";  //<======= and here
canvas.fillText(message2, 400, 100);

Also, it could be a good idea to name your context variable "context" or "cxt" instead of "canvas". It would be less confusing :)