开发者

Can I do by character text color in HTML5 Canvas?

In HTML Canvas I can set the color of a line of text using ct开发者_如何学编程x.fillStyle = 'red', which is great. What I'm trying to do is by able to set the color by letter, with only having to draw the word once.

So if the text is 'Hello different colors!', is there a way I can make the letter H red, but the rest of the text white?


I present you this workaround. Basically you output your text one char at a time, and use inbuilt measureText() function to determine the width of each letter asif it was drawn. Then we offset the position where we wanted to draw by that same amount. You can modify this snippet, to produce the effect you want.

Suppose we have HTML like so:

<canvas id="canvas" width="300" height="300"/>

And Javascript like so:

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

We'd get an output:

Can I do by character text color in HTML5 Canvas?

Check it out in action at jFiddle. I used latest Chrome.


ctx.fillStyle works as a state machine. When you say ctx.fillStyle = 'red', it will color things as red. You can do what you want by setting ctx.fillStyle = 'white', then writing the letter H, then setting ctx.fillStyle = 'red', then writing the rest of the sentence.


If you don't want to use a "round about way" function.

You can use gradients e.g. createLinearGradient. I figured out how to hard block the colors so there was no gradient just two blocks of color. This is what I did:

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 code allows text to look like this and also allows for multiple colors of text on one line of text. Check out this example: w3school example. Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜