最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin5浏览0评论

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!

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!

Share Improve this question asked Oct 29, 2011 at 23:13 user1006115user1006115 2791 gold badge5 silver badges18 bronze badges 3
  • the only way that I can think of is to split the string. To get the width use element.getBBox() raphaeljs./reference.html#Element.getBBox – Chris Ghenea Commented Nov 1, 2011 at 13:35
  • 1 also stackoverflow./questions/7881609/… – Chris Ghenea Commented Nov 2, 2011 at 3:22
  • Try stackoverflow./questions/8517191/… – Aamir Afridi Commented Aug 29, 2012 at 11:03
Add a ment  | 

1 Answer 1

Reset to default 7

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/aamir/zsS7L/

发布评论

评论列表(0)

  1. 暂无评论