Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raphael JS: how to change the color of certain letters within a text-element?

I have the following code:

        var set = paper.set();
        var text = paper.text(0, 0, 'bla1 bla2' ).attr({ fill: 'blue'});
        set.push(text);

How can I change the color of the 'bla2' to green now?

I've already tried to split the string into two text-elements and assign the coordinates of the 'bla1'+ width of the 'bla1' to the second one. It didn't work since I coundn't find out the width of 'bla1'. The second problem with this solution is that I might want to change the font-size of 'bla1 bla2' which will automatically change the width of 'bla1' and distort the position of 'bla2'.

Thanks in advance!

like image 431
user1006115 Avatar asked Oct 29 '11 23:10

user1006115


1 Answers

You can try something like this:

HTML:

<div id="canvas"></div>​

JS:

var text = "this is some colored text";
var paper = Raphael('canvas', '100%', document.documentElement.clientHeight/2 );
var colors = ["#ffc000", "#1d1d1d", "#e81c6e", "#7c7c7c", "#00aff2"];
var letterSpace = 5;
var xPos = 10;
var yPos = 10;

textNodes = text.split(' ');

for( var i=0; i < textNodes.length; ++i) {       
    var textColor = colors[i];
    var textNode = paper.text( xPos , yPos , textNodes[i]);
        textNode.attr({
            'text-anchor': 'start',
            'font-size' : 12,
            'fill' : textColor
        });
    xPos = xPos + textNode.getBBox().width + letterSpace;
}
​

Demo: http://jsfiddle.net/aamir/zsS7L/

like image 77
Aamir Afridi Avatar answered Oct 05 '22 23:10

Aamir Afridi