【问题标题】:Highlight <tspan> inside <text> of svg在 svg 的 <text> 中突出显示 <tspan>
【发布时间】:2022-11-30 03:25:26
【问题描述】:

我只想强调内部而不是全部,但下面的代码不起作用。过滤器背景颜色已填充所有节点

<!DOCTYPE html>
<html>
<body>

<svg height="30" width="200">
<defs> 
<filter id="solid">
  <feFlood flood-color="rgb(153, 255, 255)" result="bg"></feFlood>
  <feMerge>
    <feMergeNode in="bg"></feMergeNode>
    <feMergeNode in="SourceGraphic"></feMergeNode>
  </feMerge>
</filter>
</defs>
  <text x="0" y="15" fill="red">I love
  <tspan filter="url(#solid)">SVG!</tspan></text>
  Sorry, your browser does not support inline SVG.
</svg>
 
</body>
</html>

我想设置只填充文本的过滤器背景宽度和位置

【问题讨论】:

  • 不幸的是,tspan 元素上的过滤器应该使用文本元素的边界框。完成这可能需要一些 javascript。 github.com/w3c/svgwg/issues/103

标签: svg text tspan


【解决方案1】:

您可以通过 getBBox() 获取 &lt;tspan&gt; 边界框,并使用这些坐标预先添加或附加 &lt;rect&gt; 元素:

hightlightSVGText()

function hightlightSVGText() {
  let highlighted = document.querySelectorAll("svg .highlight");
  highlighted.forEach((highlight) => {
    let svg = highlight.closest("svg");
    let textParent = highlight.closest("text");
    let bb = highlight.getBBox();
    let [x, y, width, height] = [bb.x, bb.y, bb.width, bb.height];

    let highlightRect = document.createElementNS(
      "http://www.w3.org/2000/svg",
      "rect"
    );
    highlightRect.setAttribute("x", x);
    highlightRect.setAttribute("y", y);
    highlightRect.setAttribute("width", width);
    highlightRect.setAttribute("height", height);
    highlightRect.classList.add("highlightRect");
    if (highlight.classList.contains('highlight-bg')) {
      highlightRect.classList.add("highlightRect-bg");
      svg.insertBefore(highlightRect, textParent);
    } else {
      highlightRect.classList.add("highlightRect-top");
      svg.insertBefore(highlightRect, textParent.nextElementSibling);
    }
  });
}
svg {
  width: 25%;
  border: 1px solid #ccc;
}

text {
  font-size: 10px;
}

.highlightRect {
  fill: cyan;
}

.highlightRect-top {
  mix-blend-mode: screen;
}
<svg viewBox="0 0 75 50">
  <text x="0" y="15" fill="red">I love
  <tspan class="highlight">SVG!</tspan></text>
  
  <text x="0" y="30" fill="red">I love
  <tspan x="0" dy="10" class="highlight highlight-bg">SVG!</tspan></text>
</svg>

【讨论】:

    猜你喜欢
    • 2016-11-19
    • 2014-11-01
    • 1970-01-01
    • 2017-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-09
    相关资源
    最近更新 更多