Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I do by character text color in HTML5 Canvas?

Tags:

html

canvas

In HTML Canvas I can set the color of a line of text using ctx.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?

like image 618
Agent Goon Avatar asked Oct 05 '11 17:10

Agent Goon


2 Answers

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: Sample output

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

like image 169
Gleno Avatar answered Oct 22 '22 04:10

Gleno


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.

like image 43
reader_1000 Avatar answered Oct 22 '22 04:10

reader_1000