【问题标题】:Raphaeljs Substring Text attributesRaphaeljs 子字符串文本属性
【发布时间】:2012-08-27 17:41:50
【问题描述】:

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

【问题讨论】:

    标签: javascript raphael


    【解决方案1】:

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

    【讨论】:

      【解决方案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 时更改 tspan 的相对定位,即使 svg 本身可以处理此问题。可以改为使用转换字符串。示例:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-05-18
        • 2018-12-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多