38

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

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


}
4

3 回答 3

56

您必须设置文本的颜色。

像这样的东西:

const canvasObj = document.getElementById('canvas')
const context = canvasObj.getContext('2d')

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

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

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

于 2013-04-01T19:27:06.747 回答
12

您是否尝试过简单的填充样式,例如:

  canvas.fillStyle = "#ff00ff";

上的文本渲染<canvas>可能不支持高级填充样式。

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

于 2013-04-01T19:27:21.860 回答
-1

利用

canvas.fillStyle = "steelblue";
于 2020-10-15T03:29:40.790 回答