Rafael JS: how to change the color of certain letters in 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 "bla2" to green?

I already tried to split the string into two text elements and assign the coordinates 'bla1' + width 'bla1' to the second. This did not work, since I did not recognize the width of "bla1". The second problem with this solution is that I can change the font size "bla1 bla2", which will automatically change the width of "bla1" and distort the position of "bla2".

Thanks in advance!

+6
source share
1 answer

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/

+6
source

Source: https://habr.com/ru/post/900358/


All Articles