如何使用Javascript将FontAwesome渲染为SVG图像? [英] How to render FontAwesome as SVG Image using Javascript?

查看:126
本文介绍了如何使用Javascript将FontAwesome渲染为SVG图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将FontAwesome图标呈现为SVG,并使用Javascript动态地将其提供为图像源.我希望我的输出是这样的

I want to render a FontAwesome icon as an SVG dynamically provide it as an image source using Javascript. I want my output to be something like this

PS-我会自己画一个圆圈.只需一种方法即可呈现图标.

PS - I will draw the circle myself. Just need a way to render the icon.

到目前为止,我已经尝试过这种方法:

So far, I have tried this approach:

function addSVG() {

  var ele = document.getElementById("svg");

  var svg = `<svg xmlns="http://www.w3.org/2000/svg" width="50" height="50">
        <text x="4" y="15" style="font-family: FontAwesome" fill="red">&#xf007;</text>
    </svg>`

  var output = 'data:image/svg+xml;base64,' + btoa(svg)

  ele.src = output;
}
addSVG()

<head>
  <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet">
</head>

<body>
What it should look like:
  <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20">
    <text x="4" y="15" style="font-family: FontAwesome" fill="red">&#xf007;</text>
  </svg>
What it looks like:
  <img id="svg">
</body>

如您所见,如果没有Javascript(仅在HTML中使用SVG),它就可以正常工作.

As you can see, without the Javascript (just using SVG in HTML) it works fine.

推荐答案

从XML引用外部CSS样式表时,不能使用<img>元素.您需要使用<object>元素,例如此答案推荐,并在<?xml-stylesheet?>前添加

You can't use an <img> element when referencing an external CSS stylesheet from XML. You need to use an <object> element like this answer recommends, and prepend an <?xml-stylesheet?> processing instruction in order for the SVG+XML blob to be able to find the FontAwesome glyph for the HTML entity &#xf007;.

function addSVG() {
  var ele = document.getElementById("svg");
  var svg = `
    <?xml-stylesheet type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"?>
    <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20">
        <text x="4" y="15" style="font-family: FontAwesome" fill="red">&#xf007;</text>
    </svg>`
  var output = `data:image/svg+xml;utf8,${svg}`

  ele.type = 'image/svg+xml';
  ele.data = output;
}
addSVG()

<head>
  <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet">
</head>

<body>
  What it should look like:
  <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20">
    <text x="4" y="15" style="font-family: FontAwesome" fill="red">&#xf007;</text>
  </svg> What it looks like:
  <object id="svg"></object>
</body>

这篇关于如何使用Javascript将FontAwesome渲染为SVG图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆