根据要使用的语言显示svg文本

问题描述

如何使要显示的文本根据所使用的语言而有所不同。

例如文本在以下位置的示例:

Spanish I would like to use the text: Hola!

Italian I would like to use the text: Ciao!

English I would like to use the text: Hi!

如果未传递任何语言,则为认语言,例如英语。

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg height="30" width="200">
  <text x="0" y="15" fill="blue">Hi!</text>
</svg>

语言选择示例,该语言可以在cookie或会话中。

或者可以将其作为参数传递到文件name.svg?Lang=es

解决方法

您可以使用开关元素。将浏览器的语言设置更改为首选意大利语或西班牙语,以查看文本更改。

<svg width="100%" height="100%" viewBox="0 100 600 300">
  <switch font-size="18">
        <g systemLanguage="en">
          <text x="20" y="220" xml:lang="en-US">Why can't they just speak English ?</text>
          <text x="230" y="150" xml:lang="en">English (US)</text>
        </g>
        <g systemLanguage="es">
          <text x="20" y="220" xml:lang="es-ES" font-size="18">¿Por qué no pueden simplemente hablar en castellano ?</text>
          <text x="230" y="150" xml:lang="en">Spanish (ES)</text>
        </g>
        <g systemLanguage="it">
          <text x="20" y="220" xml:lang="it" font-size="18">Perchè non possono semplicemente parlare italiano ?</text>
          <text x="230" y="150" xml:lang="en">Italian</text>
        </g>
    </switch>
</svg>

,

在现代浏览器中,您可以使用自定义元素动态生成SVG

使用罗伯茨systemLanguage增强SVG
https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/systemLanguage

对于React,您必须在每个自定义元素周围添加额外的包装器代码,
React仅支持此W3C标准for 71%
使用W3C标准自定义元素API的所有其他框架都是100%BFF

customElements.define('svg-text',class extends HTMLElement {
  static get observedAttributes() {
    return ["bgfill","width","height","stroke","fill","text","x","y","fontsize","rotate"
    ]; // update whenever these attributes change
  }
  connectedCallback() {
    let [bgfill = "pink",width = 200,height = 150,stroke = "none",fill = "green",text = "Hello",x = "50%",y = "50%",fontsize = "1em",rotate = "0"
    ] = this.constructor.observedAttributes.map(x => this.getAttribute(x) || undefined);

    this.innerHTML = `<svg width='${width}' height='${height}'` +
      `xmlns='http://www.w3.org/2000/svg'>` +
      `<rect width='100%' height='100%' fill='${bgfill}'/>` +
      `<text dominant-baseline='middle' text-anchor='middle' font-size='${fontsize}'` +
      ` x='${x}' y='${y}' fill='${fill}' ` +
      ` stroke='${stroke}' transform='rotate(${rotate} ${width/2} ${height/2})'>${text}</text></svg>`
  }

  attributeChangedCallback(name,oldValue,newValue) {
    if (this.isConnected) this.connectedCallback();
  }
});
// example changing attribute
setTimeout(() => {
  document.querySelector("svg-text").setAttribute("text","Ola!");
},21e2)
<svg-text bgfill='lightblue' fill="blue" width="100" fontsize="3em" height="100">
</svg-text>

<svg-text fill="green" width="75" height="25" text="Hallo">
</svg-text>

<svg-text bgfill="gold" fill="red" width="50" text="Bonjour" rotate="90" fontsize="2em">
</svg-text>