Skip to content Skip to sidebar Skip to footer

Raphaeljs Substring Text Attributes

I was wondering if it's possible to change the attributes of a substring of the text object in Raphael. For example, I want to bold the word wizard in the following string 'The ma

Solution 1:

Fonts are set at the element level, much like in regular html. In order to apply a separate font or style to a specific word, you would need to break your 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" });

Solution 2:

A problem with the solution by gilly3 is that the x-coordinate of the elements is absolute. When changing the text, for example bold.attr({"text":"sorcerer"}), the elements will overlap.

An alternative solution is to compose a text element out of custom tspan elements with relative positioning. This is also a bit cleaner from an object model perspective. However, it does require some direct manipulation of the text element. 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 can change relative positioning of tspans when altering x,y,dx,dy of the parent element, even though svg itself can handle this. A transform string can be used instead. Example:

content.node.setAttribute("x",500); //workscontent.attr({"x":500});  //undesired resultcontent.transform("t100");   //works

Post a Comment for "Raphaeljs Substring Text Attributes"