Raphaeljs子串文本属性

时间:2011-10-24 20:31:23

标签: javascript raphael

我想知道是否可以在Raphael中更改文本对象的子字符串的属性。例如,我想在下面的字符串中加粗“向导”这个词:“魔法向导统治世界!”在raphael文本对象中。我已经看过使用Raphael.print()方法,我需要文本中的一些属性来代码的其他部分。

2 个答案:

答案 0 :(得分:4)

字体在元素级别设置,与常规html非常相似。为了将单独的字体或样式应用于特定单词,您需要将文本分成单独的元素。

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" });

答案 1 :(得分:2)

gilly3解决方案的一个问题是元素的x坐标是绝对的。更改文本时,例如bold.attr({"text":"sorcerer"}),元素将重叠。

另一种解决方案是使用相对定位从自定义tspan元素中组合文本元素。从对象模型的角度来看,这也有点清晰。但是,它确实需要对文本元素进行一些直接操作。代码:

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 ";

免责声明:Raphael可以在更改父元素的x,y,dx,dy时更改tspans的相对位置,即使svg本身可以处理此问题。可以使用变换字符串。例如:

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