Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
446 views
in Technique[技术] by (71.8m points)

javascript - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...