SVG variable text

2019-09-20 09:07发布

I know little about SVG but I'm trying to make the text parameter variable, so I could iterate and create SVG Markup's which vary solely by (variable) text. This is what I can do (borrowed from the site whose API I'm using)

'<svg  width="24" height="24" xmlns="http://www.w3.org/2000/svg">' +
  '<rect stroke="black" fill="${FILL}" x="1" y="1" width="22" height="22" />' +
  '<text x="12" y="18" font-size="12pt" font-family="Arial" font-weight="bold" ' +
  'text-anchor="middle" fill="${STROKE}" >hello world
  </text></svg>'

But this is what I would like (or something that works like it):

'<svg  width="24" height="24" xmlns="http://www.w3.org/2000/svg">' +
  '<rect stroke="black" fill="${FILL}" x="1" y="1" width="22" height="22" />' +
  '<text x="12" y="18" font-size="12pt" font-family="Arial" font-weight="bold" ' +
  'text-anchor="middle" fill="${STROKE}" >"${TEXT}"</text></svg>'

so I can dynamically change the text.

标签: svg
2条回答
Viruses.
2楼-- · 2019-09-20 09:53

You actually can use ${TEXT}, and it does work (except for IE).

The name of this is template literal:

Template literals are string literals allowing embedded expressions.

However, for this to work, you should have enclosed the whole string with back-ticks (`).

Here is a working demo using your string (with little changes):

var FILL = "tan", STROKE = "black", TEXT = "Hello World";

var svgMarkup = `<svg xmlns="http://www.w3.org/2000/svg" width="100" height="24" 
xmlns="http://www.w3.org/2000/svg"><rect stroke="black" fill="${FILL}" x="1" y="1" 
width="22" height="22" /><text x="12" y="18" font-size="12pt" font-family="Arial" 
font-weight="bold" text-anchor="start" fill=${STROKE}>${TEXT}</text></svg>`;

var div = document.getElementById("foo");
div.innerHTML = svgMarkup;
<div id="foo"></div>

查看更多
家丑人穷心不美
3楼-- · 2019-09-20 10:04

Ok I figured it out; in retrospect, it was kind of a stupid question

查看更多
登录 后发表回答