是否有一种方法可以在SVG文本路径上的单个字母周围绘制矩形

Is there a way to draw a rectangle around single letters on a SVG textpath

本文关键字:路径 文本 单个字 绘制 周围 SVG 一种 方法 是否      更新时间:2023-09-26

是否有可能在SVG文本路径的单个字母后面绘制矩形?我试着把我要做的事描绘出来。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>

这个怎么样?它使用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>

您将需要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度的角度向上画。这将在文本路径上定位每个矩形的基底,但它不包括字母的"下降线"。

要做到这一点,我决定它会更容易切换回<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 &Firefox和IE11/10/9(通过开发者的模拟器)

如果您真的,真的想这样做;)....它可以通过使用具有unicode字符#96xx系列的'background' 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>