Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
350 views
in Technique[技术] by (71.8m points)

html - Using Google Fonts with SVG <object>

I'm embedding SVGs in my page with the <object> tag, and they're supposed to utilize Google Fonts (e.g. Roboto). However, the SVGs aren't picking these fonts up and instead default to system fonts.

What am I doing wrong? Does every SVG require that the font itself be embedded in <style>?

Example code:

<head>
    <link href='https://fonts.googleapis.com/css?family=Roboto:400,100,100italic,300,300italic,400italic,500,500italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'>
</head>

<body>
    <object width="250" height="200" type="image/svg+xml" data="img/popup_image.svg"></object>
</body>

SVG snippet:

<text font-size="14" fill="#333" font-family="Roboto">Words go here</text>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The browser treats SVG text as regular HTML text. In other words, any text elements in your SVG must be styled like normal HTML elements (like a <span>, for example). You need to embed your font in your SVG in the form of a CSS @import. Look through the XML of your SVG for the <defs> section. Then, add this code to it:

<defs>
  <style type="text/css">
    @import url('https://fonts.googleapis.com/css?family=Roboto:400,100,100italic,300,300italic,400italic,500,500italic,700,700italic,900,900italic');
 </style>
</defs>

Next, update your <text> element to be like this:

<text font-size="14" fill="#333" style="font-family: 'Roboto';">
   Words go here
</text>

If you want more information about this, you might try this website: http://nimbupani.com/about-fonts-in-svg.html. It has some pretty good information on fonts in embedded SVGs. A working example of this can be found here: https://github.com/marians/test-webfonts-in-svg.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...