Alex Brodersen
Alex Brodersen

Reputation: 73

p5.js: change text color in for a single word in a sentence

I want to change the color of a single word in a string that I am drawing to the canvas, without having to manually fiddle with text locations and have multiple "text()" function calls.

Is this possible in p5?

Example:

textAlign(CENTER);
text("I want THIS to be in green.",50,50);

Where "THIS" is a different color from the rest of the sentence.

I could use multiple text calls, such as

textAlign(CENTER);
fill(255,0,0);
text("I want ",50,50);
fill(0,255,0);
text("THIS",50 + widthOfFirstPart,50)
fill(255,0,0);
text("to be in green.",50 + widthOfSecondPart,50);

But that seems clunky, UNLESS there is a good way to solve for the "widthOfFirstPart" and "widthOfSecondPart" variables.

Upvotes: 1

Views: 5943

Answers (1)

Rabbid76
Rabbid76

Reputation: 210878

I recommend to create a function, which handles an array of tuples, consisting of text and color.

e.g.:

var red = [255, 0, 0];
var green = [0, 255, 0];
var string = [
    ["I want ", red],
    ["THIS ", green],
    ["to be in green.", red]
];

Process the array in a loop, calculate the length of each text part. Sum the length of the text parts, to determine the start position of each part. Of course the text has to be aligned RIGHT (it would be possible to extend the code, to handle other alignments too):

function drawtext( x, y, text_array ) {

    var pos_x = x;
    for ( var i = 0; i < text_array.length; ++ i ) {
        var part = text_array[i];
        var t = part[0];
        var c = part[1];
        var w = textWidth( t );
        fill( c );
        text( t, pos_x, y);
        pos_x += w;
    }
}

function setup() {
    createCanvas( 500, 200 );
}

function draw() {
    background( 126, 192, 238 );
  
    textAlign(LEFT);
    
    var red = [255, 0, 0];
    var green = [0, 255, 0];
    var string = [
        ["I want ", red],
        ["THIS ", green],
        ["to be in green.", red]
    ];
    drawtext(50, 50, string );
}

function drawtext( x, y, text_array ) {
  
    var pos_x = x;
    for ( var i = 0; i < text_array.length; ++ i ) {
        var part = text_array[i];
        var t = part[0];
        var c = part[1];
        var w = textWidth( t );
        fill( c );
        text( t, pos_x, y);
        pos_x += w;
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/p5.js"></script>

Upvotes: 4

Related Questions