有没有办法在SVG文本路径上围绕单个字母绘制一个矩形

时间:2014-03-29 21:13:04

标签: javascript html css svg

是否有可能在SVG文本路径的单个字母后面绘制矩形?我试过draw an image of what I am trying to do。 SVG是HTML页面的一部分。似乎没有办法用CSS获取文本路径,但也许有一种使用javascript的方法?

这是我的html / svg代码:

<svg id="foo" width="100%" height="100%" viewBox="-30 -220 1000 800"
xmlns="http://www.w3.org/2000/svg" 
xmlns:xlink="http://www.w3.org/1999/xlink">

    <defs>
        <path id="MyPath"
        d="M 100 200 
        C 200 100 300   0 400 100
        C 500 200 600 300 700 200
        C 800 100 900 100 900 100" />
    </defs>

    <use xlink:href="#MyPath" fill="none" stroke="black"  />

    <text font-family="arial" font-size="140" >
        <textPath xlink:href="#MyPath" startOffset="20" dy="10">
            Lorem ipsum 
        </textPath>
    </text>

</svg>

3 个答案:

答案 0 :(得分:1)

this...如何使用SVG DOM获取字符框,然后在鼠标下方的字符后面绘制一个矩形。

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width='400' height='400'>
<script><![CDATA[
  function details(evt) {
    var letters='Move mouse over letters...';
    var pathLetters='ABCDEFGHIJKLMNOPQRSTUVWXYZ';

    var svgdoc=evt.target.ownerDocument;
    var xm=evt.clientX;
    var ym=evt.clientY;
    var text=svgdoc.getElementById('text');
    var d=text.getStartPositionOfChar(1);
    d.x=xm;
    d.y=ym;
    var p=text.getCharNumAtPosition(d);
    if (p >= 0) {
      var f=text.getExtentOfChar(p);
      var node=document.createTextNode('You are on character '+letters.substring(p,p+1));
      var letter=svgdoc.getElementById('letter');
      letter.replaceChild(node,letter.firstChild);
      var outline=svgdoc.getElementById('outline');
      outline.setAttribute('x',f.x);
      outline.setAttribute('y',f.y);
      outline.setAttribute('width',f.width);
      outline.setAttribute('height',f.height)
    }
    var textPath=svgdoc.getElementById('textPath');
    p=textPath.getCharNumAtPosition(d);
    if (p >= 0) {
      var f=textPath.getExtentOfChar(p);
      var node=document.createTextNode('You are on character '+pathLetters.substring(p,p+1));
      var letter=svgdoc.getElementById('letter');
      letter.replaceChild(node,letter.firstChild);
      var outline=svgdoc.getElementById('outline');
      outline.setAttribute('x',f.x);
      outline.setAttribute('y',f.y);
      outline.setAttribute('width',f.width);
      outline.setAttribute('height',f.height)
    }
  }
  function zero(evt)
  {
    var svgdoc=evt.target.ownerDocument;
    var outline=svgdoc.getElementById('outline');
    outline.setAttribute('x',0);
    outline.setAttribute('y',0);
    outline.setAttribute('width',0);
    outline.setAttribute('height',0);
    var letter=svgdoc.getElementById('letter');
    node=document.createTextNode('You are on character ');
    letter.replaceChild(node,letter.firstChild);
  }
]]></script>
  <defs>
      <path id="s3" d="M 10,200 Q 100,125 200,180 Q 340,260 400,140" />
  </defs>
  <rect id='outline' x='0' y='0' width='0' height='0' style='stroke:green;fill:yellow'/>
  <g>
    <text onmousemove='details(evt)' onmouseout='zero(evt)' id='text' x='200' y='100' style='text-anchor:middle;font-size:24pt;font-family:Arial;fill:red'>Move mouse over letters...</text>
    <text style='font-size:20pt;font-family:Arial;fill:red'><textPath onmousemove='details(evt)' onmouseout='zero(evt)' id='textPath' xlink:href="#s3">ABCDEFGHIJKLMNOPQRSTUVWXYZ</textPath>
    </text>
    <text id='letter' x='20' y='250' style='text-anchor:start;font-size:16pt;fill:blue'>You are on character </text>
  </g>
</svg>

答案 1 :(得分:1)

你需要Javascript,但它不像前面的例子那样复杂相当

所有文本元素都有一组相关的接口函数来定位每个字符:

http://www.w3.org/TR/SVG11/text.html#InterfaceSVGTextContentElement

最简单的方法是使用getExtentOfChar(i)查找每个字符字形的边界框矩形。这是@Robert Longson的例子中使用的方法。没有所有额外的事件处理代码,它可以简化为:

var texts = document.getElementsByClassName("backgroundRect");
var svgNS ="http://www.w3.org/2000/svg";
for (var i=0, max= texts.length; i<max; i++) {

    var t = texts[i];

    var g = document.createElementNS(svgNS, "g");

    for (var j=0, nchar=t.getNumberOfChars(); j<nchar; j++) {
        var r = t.getExtentOfChar(j);
        var re = document.createElementNS(svgNS, "rect");
        re.setAttribute("width", r.width);
        re.setAttribute("height", r.height);
        re.setAttribute("x", r.x);
        re.setAttribute("y", r.y);
        g.insertBefore(re, null);        
    }

    t.parentNode.insertBefore(g, t);
}

http://fiddle.jshell.net/T5qWb/1/

限制是边界框是最小的矩形,它将包含原始水平和垂直坐标中的字母,而不是旋转的矩形,因此矩形大于字母和重叠

要找出一个紧密边界的矩形,您需要使用.getStartPositionOfChar(i).getEndPositionOfChar(i)和一些几何体:

var texts = document.getElementsByClassName("backgroundRect");
var svgNS ="http://www.w3.org/2000/svg";
for (var i=0, max= texts.length; i<max; i++) {

    var t = texts[i];

    var g = document.createElementNS(svgNS, "g");
    g.setAttribute("class", "textBackground");

    for (var j=0, nchar=t.getNumberOfChars(); j<nchar; j++) {
        var p = document.createElementNS(svgNS, "path");

        var start = t.getStartPositionOfChar(j),
            end = t.getEndPositionOfChar(j),
            height = parseFloat(getComputedStyle(t)["fontSize"]),
            vector = [(end.x - start.x), (end.y - start.y)],
            aspect = height / 
                    Math.sqrt(vector[0]*vector[0] + vector[1]*vector[1]),
            normal = [vector[1]*aspect, -vector[0]*aspect];

        var d = ["M", [start.x, start.y],
                 "l", normal, vector, [-normal[0], -normal[1]],
                 "z"
                 ].join(" ");
        p.setAttribute("d", d);
        g.insertBefore(p, null);        
    }

    t.parentNode.insertBefore(g, t);
} 

http://fiddle.jshell.net/T5qWb/2/

我这次使用的是<path>而不是<rect>,使用相对坐标沿着角色的基线绘制直线,然后在90度的距离内向上移动1em。这会将每个矩形的基础定位在文本路径上,但它不会覆盖字母的“下降”。

为此,我决定更容易切换回<rect>元素,并使用变换来定位矩形。我将矩形转换为起点,根据.getRotationOfChar(i)旋转它,然后将其从基线转换出来。唯一的限制是我必须硬编码估计角色的高度应该低于基线,因为我无法找出任何方法来计算给定字体

var texts = document.getElementsByClassName("backgroundRect");
var svgNS ="http://www.w3.org/2000/svg";
for (var i=0, max= texts.length; i<max; i++) {

    var t = texts[i];

    var g = document.createElementNS(svgNS, "g");
    g.setAttribute("class", "textBackground");


    for (var j=0, nchar=t.getNumberOfChars(); j<nchar; j++) {
        var re = document.createElementNS(svgNS, "rect");

        var start = t.getStartPositionOfChar(j),
            end = t.getEndPositionOfChar(j),
            angle = t.getRotationOfChar(j),
            height = parseFloat(getComputedStyle(t)["fontSize"]),
            vector = [(end.x - start.x), (end.y - start.y)],
            width = Math.sqrt(vector[0]*vector[0] + vector[1]*vector[1]),
            aspect = height / width,
            normal = [vector[1]*aspect, -vector[0]*aspect],
            baseline = 0.2;

        re.setAttribute("height", height);
        re.setAttribute("width", width);
        re.setAttribute("transform", 
                       ["translate(", [start.x, start.y], ")",
                        "rotate(", angle, ")", 
                        "translate(0", -height*(1-baseline), ")" 
                        ].join(" ")
                       );
        g.insertBefore(re, null);        
    }

    t.parentNode.insertBefore(g, t);
}

http://fiddle.jshell.net/T5qWb/3/

经过测试,所有界面方法都在最新的Chrome&amp; Firefox和IE11 / 10/9(通过开发人员的模拟器)。

答案 2 :(得分:0)

如果你真的,真的想要这样做;)....它可以通过使用&#39;背景&#39;来实现。带有 unicode 字符#96xx系列的textPath。但是,要使其与父字符对齐,您必须开发一个表,该表将选择与父字符匹配的正确字符和大小。这需要一些javascript,一些耐心定义角色的边界框,以及理解文本对齐。当然,不同浏览器渲染它的方式将挑战你的理智。

嗯......我想如果你能创造这个,你就会有一些东西要吹嘘。

以下是使用textPath的概念的粗略示例。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Unicode textPath character background</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body style='padding:10px;font-family:arial'>
<center>
<h4>Unicode characters as textPath character background</h4>
#96xx series
<div style='color:blue;width:90%;background-color:gainsboro;text-align:justify;padding:10px;border-radius:6px;'>
  &#9605;
  &#9605;
  &#9605;
  &#9605;
  &#9605;
  &#9605;
 &nbsp;
 &nbsp;
 &nbsp;
 &nbsp;
  &#9606;
  &#9606;
  &#9606;
  &#9606;
  &#9606;
  &#9606;
 &nbsp;
 &nbsp;
 &nbsp;
 &nbsp;

  &#9607;
  &#9607;
  &#9607;
  &#9607;
  &#9607;
  &#9607;
 &nbsp;
 &nbsp;
 &nbsp;
 &nbsp;

  &#9608;
  &#9608;
  &#9608;
  &#9608;
  &#9608;
  &#9608;
 &nbsp;
 &nbsp;
 &nbsp;
 &nbsp;
  &#9609;
  &#9609;
  &#9609;
  &#9609;
  &#9609;
  &#9609;
 &nbsp;
 &nbsp;
 &nbsp;
 &nbsp;

  &#9610;
  &#9610;
  &#9610;
  &#9610;
  &#9610;
 &nbsp;
 &nbsp;
 &nbsp;
 &nbsp;

  &#9611;
  &#9611;
  &#9611;
  &#9611;
  &#9611;
 &nbsp;
 &nbsp;
 &nbsp;
 &nbsp;

  &#9612;
  &#9612;
  &#9612;
  &#9612;
  &#9612;
</div>
<div id="svgDiv" style='background-color:lightgreen;width:400px;height:400px;'>
<svg id="foo" width="100%" height="100%" viewBox="-30 -220 1000 800"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
    <defs>
        <path id="MyPath"
        d="M 100 200
        C 200 100 300   0 400 100
        C 500 200 600 300 700 200
        C 800 100 900 100 900 100" />
    </defs>

    <use xlink:href="#MyPath" fill="none" stroke="black"  />

    <text fill="blue"  font-size="140" >
    <textPath xlink:href="#MyPath" startOffset="20" dy="10">
    &#9607;&#9607;&#9607;&#9607;&#9607;  &#9607;&#9607;&#9607;&#9607;&#9607;
    </textPath>
    </text>
    <text  font-family="arial" font-size="140" >
    <textPath xlink:href="#MyPath" startOffset="20" dy="10">
    Lorem ipsum
    </textPath>
    </text>
</svg>
</div>
 </center>
</body>
</html>