Skip to content

Commit f0479a6

Browse files
committed
Update getSvgImage() example (#355)
1 parent a1e9948 commit f0479a6

File tree

1 file changed

+12
-8
lines changed

1 file changed

+12
-8
lines changed

web/convert.rst

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -318,18 +318,22 @@ into the SVG image.
318318
'use[data-c]{stroke-width:3px}'
319319
].join('');
320320
const xmlDeclaration = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>';
321+
const SVGXMLNS = 'http://www.w3.org/2000/svg';
321322
322323
async function getSvgImage(math, options = {}) {
323324
const adaptor = MathJax.startup.adaptor;
324325
const result = await MathJax.tex2svgPromise(math, options);
325-
let svg = adaptor.tags(result, 'svg')[0];
326-
svg = (svg.match(/^<svg.*?><defs>/)
327-
? svg.replace(/<defs>/, `<defs><style>${svgCss}</style>`)
328-
: svg.replace(/^(<svg.*?>)/, `$1<defs><style>${svgCss}</style></defs>`));
329-
svg = svg.replace(/ (?:role|focusable|aria-hidden)=".*?"/g, '')
330-
.replace(/"currentColor"/g, '"black"');
331-
return xmlDeclaration + '\n' + svg;
332-
}
326+
const svg = adaptor.tags(result, 'svg')[0];
327+
const defs = adaptor.tags(svg, 'defs')[0] || adaptor.append(svg, adaptor.create('defs'));
328+
adaptor.append(defs, adaptor.node('style', {}, [adaptor.text(svgCss)], SVGXMLNS));
329+
adaptor.removeAttribute(svg, 'role');
330+
adaptor.removeAttribute(svg, 'focusable');
331+
adaptor.removeAttribute(svg, 'aria-hidden');
332+
const g = adaptor.tags(svg, 'g')[0];
333+
adaptor.setAttribute(g, 'stroke', 'black');
334+
adaptor.setAttribute(g, 'fill', 'black');
335+
return xmlDeclaration + '\n' + adaptor.serializeXML(svg);
336+
}
333337
334338
This defines a function :meth:`getSvgImage()` that takes a math string
335339
and returns a self-contained serialized SVG image of the math.

0 commit comments

Comments
 (0)