You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

SVG文件文本无法渲染的技术求助

SVG文件文本无法渲染的技术求助

嗨,我帮你找到了SVG文本不显示的核心问题,以及对应的修复方案:

你的文本不显示是因为错误地使用了<use>元素引用<defs>里的空文本,还试图在<use>标签内直接加文本内容——这不符合SVG的规范:

  • <defs>里的元素默认是预定义的复用模板,本身不会被渲染;
  • <use>元素的作用是完全复制你引用的原元素,你在<use>标签里写的Start/End根本不会被当作文本内容解析,而你引用的原文本<text id="timeVal">本身就是空的,所以最终看不到任何文字。

下面是两种修复方式,推荐第一种更直观易用的:


方案1:移出defs中的空文本,直接创建独立文本元素

把样式保留在<style>中,然后在需要文本的位置直接写<text>元素,通过class应用你定义好的timestamp样式即可。修改后的完整SVG代码如下:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg width="210mm" height="297mm" viewBox="0 0 210 297" version="1.1" id="svg1" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg">
  <style>
    .timestamp { font: bold 24px sans-serif; fill: black; }
  </style>
  <defs id="defs1">
    <radialGradient id="pillGradient" cx="29.671396" cy="44.50275" fx="29.671396" fy="44.50275" r="3.9697015" gradientUnits="userSpaceOnUse" gradientTransform="matrix(1.6777305,0.01756636,-0.01425945,1.3614585,-19.408916,57.54193)" />
    <path id="slideLine" d="M 25,120 h 180" style="fill:none;stroke:#d8d8d8;stroke-width:1.99999;stroke-linecap:square;stroke-dasharray:none;stroke-opacity:1" />
    <path id="leadLine" d="M 25, 115 v -10 h 0 v -10" style="fill:none;fill-opacity:1;stroke:#000000;stroke-width:1;stroke-linecap:square;stroke-dasharray:none;stroke-opacity:1" />
    <circle id="pill" cx="25" cy="120" r="3" style="fill:#0096a2;fill-opacity:1;stroke:url(#pillGradient);stroke-width:1;stroke-linecap:square;stroke-dasharray:none;stroke-opacity:1" />
  </defs>
  <g id="dateRangeCtl">
    <use href="#slideLine" id="slider" />
    <use href="#pill" id="leftPill" />
    <use href="#pill" id="rightPill" x="100" />
    <use href="#leadLine" id="leftLeadLine" />
    <!-- 直接创建带内容的text元素,应用预设样式 -->
    <text xml:space="preserve" class="timestamp" x="27" y="95" id="startTime">Start</text>
    <use href="#leadLine" id="rightLeadLine" x="100" />
    <text xml:space="preserve" class="timestamp" x="127" y="95" id="endTime">End</text>
  </g>
</svg>

方案2:复用文本基础属性(不推荐,可读性差)

如果你确实想复用文本的位置、字体等基础属性,可以在<defs>里保留空文本模板,然后用<text>元素引用它,再通过<tspan>添加内容。这种方式兼容性一般,代码可读性也不如方案1,仅作参考:

<!-- 仅修改defs和文本相关部分 -->
<defs id="defs1">
  <!-- 其他预定义元素保留 -->
  <text xml:space="preserve" class="timestamp" x="27" y="95" id="timeVal"></text>
</defs>
<g id="dateRangeCtl">
  <!-- 其他元素保留 -->
  <use href="#leadLine" id="leftLeadLine" />
  <!-- 通过text引用模板,用tspan添加内容 -->
  <text href="#timeVal" id="startTime">
    <tspan>Start</tspan>
  </text>
  <use href="#leadLine" id="rightLeadLine" x="100" />
  <text href="#timeVal" id="endTime" x="100">
    <tspan>End</tspan>
  </text>
</g>

把修改后的代码替换你的原文件,不管是Inkscape还是Firefox都应该能正常显示文本了。如果需要调整文本位置,直接修改对应<text>元素的x/y属性即可,方案1的灵活性会更高。

内容来源于stack exchange

火山引擎 最新活动