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?
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:
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With