在HTML5 <canvas> </canvas>上更改fillText()的颜色

时间:2013-04-01 19:11:59

标签: javascript html5 html5-canvas

我正在尝试更改画布上每行消息的颜色,但到目前为止还没有成功。我试过为每一个创建变量,但仍然没有运气。任何帮助将不胜感激。

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


}

3 个答案:

答案 0 :(得分:32)

你必须设置文本的颜色。

这样的事情:

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

此外,将上下文变量命名为“context”或“cxt”而不是“canvas”可能是个好主意。这将不那么令人困惑:)

答案 1 :(得分:4)

您是否尝试过简单的fillStyles,如:

  canvas.fillStyle = "#ff00ff";

<canvas>上的文字呈现可能不支持高级填充样式。

在呈现每条消息之前,只需设置新的fillStyle。

答案 2 :(得分:0)

使用

canvas.fillStyle = "steelblue";