Raphaeljs Substring文本属性

Raphaeljs Substring Text attributes

本文关键字:属性 文本 Substring Raphaeljs      更新时间:2023-09-26

我想知道是否有可能改变拉斐尔文本对象的子字符串的属性。例如,我想在raphael文本对象中,将下面字符串"the magical wizard统治世界!"中的单词wizard加粗。我已经看过使用Raphael.print()方法,我需要一些来自文本的属性用于代码的其他部分。

字体是在元素级别设置的,就像在常规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" });

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

另一种解决方案是用相对定位的自定义tspan元素组成一个文本元素。从对象模型的角度来看,这也更简洁一些。但是,它确实需要对text元素进行一些直接操作。代码:

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

免责声明:当改变父元素的x,y,dx,dy时,Raphael可以改变tspan的相对位置,尽管svg本身可以处理这个。可以使用转换字符串代替。例子:

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