Raphaeljs substring text attributes

I was wondering if it is possible to change the substring attributes of a text object in Raphael. For example, I want the master of words in the following line in bold: "The magical wizard rules the world!" in the raphael text object. I reviewed the use of the Raphael.print () method, and I need some text attributes for other parts of the code.

+2
source share
2 answers

Fonts are set at the element level, as in regular html. To apply a single font or style to a specific word, you need to break the text into separate elements.

var start = paper.text(20, 20, "The magical "); start.attr({ "text-anchor": "start" }); var startBox = start.getBBox(); var bold = paper.text(startBox.width + startBox.x, 20, "wizard "); bold.attr({ "text-anchor": "start", "font-weight": "bold" }); var boldBox = bold.getBBox(); var end = paper.text(boldBox.width + boldBox.x, 20, "ruled the world!"); end.attr({ "text-anchor": "start" }); 
+4
source

The problem with gilly3's solution is that the x-coordinate of the elements is absolute. When you change text, for example bold.attr({"text":"sorcerer"}) , the elements will overlap.

An alternative solution is to compose a text element from custom tspan elements with relative positioning. It is also a bit cleaner in terms of the object model. However, this requires some direct manipulation of the text element. The code:

 var content = paper.text(20, 20, "The magical").attr({ "text-anchor": "start" }); var txt1=Raphael._g.doc.createTextNode(" wizard "); var txt2=Raphael._g.doc.createTextNode("ruled the world!"); var svgNS = "http://www.w3.org/2000/svg"; var ts1 = Raphael._g.doc.createElementNS(svgNS, "tspan"); var ts2 = Raphael._g.doc.createElementNS(svgNS, "tspan"); ts1.setAttribute("font-weight","bold"); ts1.appendChild(txt1); ts2.appendChild(txt2); content.node.appendChild(ts1); content.node.appendChild(ts2); content.node.children[1].textContent=" sorcerer "; 

Disclaimer: Raphael may change the relative positioning of tspans when x,y,dx,dy parent element changes, although svg itself can handle this. Instead, a conversion string can be used. Example:

 content.node.setAttribute("x",500); //works content.attr({"x":500}); //undesired result content.transform("t100"); //works 
+2
source

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


All Articles