【发布时间】:2011-10-05 17:39:36
【问题描述】:
在 HTML Canvas 中,我可以使用 ctx.fillStyle = 'red' 设置一行文本的颜色,这很棒。我想要做的是能够按字母设置颜色,只需要画一次单词。
如果文本是“你好,不同的颜色!”,有没有办法让字母 H 变成红色,而其余的文本变成白色?
【问题讨论】:
在 HTML Canvas 中,我可以使用 ctx.fillStyle = 'red' 设置一行文本的颜色,这很棒。我想要做的是能够按字母设置颜色,只需要画一次单词。
如果文本是“你好,不同的颜色!”,有没有办法让字母 H 变成红色,而其余的文本变成白色?
【问题讨论】:
我向您介绍这个解决方法。基本上,您一次输出一个字符,并使用内置的measureText() 函数来确定每个字母的宽度,就像它被绘制一样。然后我们将要绘制的位置偏移相同的量。你可以修改这个sn-p,来产生你想要的效果。
假设我们有这样的 HTML:
<canvas id="canvas" width="300" height="300"/>
而 Javascript 是这样的:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
function randomColor(){
var r = Math.floor(Math.random()*256);
var g = Math.floor(Math.random()*256);
var b = Math.floor(Math.random()*256);
return "rgb("+ r + "," + g + "," + b +")";
}
function texter(str, x, y){
for(var i = 0; i <= str.length; ++i){
var ch = str.charAt(i);
ctx.fillStyle = randomColor();
ctx.fillText(ch, x, y);
x += ctx.measureText(ch).width;
}
}
texter("What's up?", 10, 30);
我们会得到一个输出:
在行动中查看at jFiddle。我用的是最新的 Chrome。
【讨论】:
ctx.fillStyle 用作状态机。当您说ctx.fillStyle = 'red' 时,它会将事物着色为红色。你可以通过设置ctx.fillStyle = 'white',然后写字母H,然后设置ctx.fillStyle = 'red',然后写下句子的其余部分来做你想做的事情。
【讨论】:
如果您不想使用“迂回”功能。
您可以使用渐变,例如创建线性渐变。我想出了如何硬块颜色所以没有渐变只有两个颜色块。这就是我所做的:
var gradient = ctx.createLinearGradient(0, 0, 300, 0);
gradient.addColorStop(0, "red");
gradient.addColorStop(0.5, "red");
gradient.addColorStop(0.5, "blue");
gradient.addColorStop(1, "blue");
ctx.fillStyle = gradient;
此代码允许文本看起来像this,并且还允许在一行文本中使用多种颜色的文本。看看这个例子:w3school example。希望这会有所帮助。
【讨论】:
addColorStop 增量:jsfiddle.net/yasuom8g