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

时光怂恿深爱的人放手 提交于 2019-11-28 03:52:23

问题


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!


回答1:


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/



来源:https://stackoverflow.com/questions/7942269/raphael-js-how-to-change-the-color-of-certain-letters-within-a-text-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!