gpt4 book ai didi

javascript - 如何使用 Javascript 将 FontAwesome 渲染为 SVG 图像?

转载 作者:太空狗 更新时间:2023-10-29 15:02:55 24 4
gpt4 key购买 nike

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

output

PS - 我会自己画圆圈。只需要一种方法来呈现图标。

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

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)它工作正常。

最佳答案

为什么在 img 标签中需要它? SVG 是图像!您不需要它来放入其他东西。

可能我不知道你的什么,但我认为这只是你的一个坏主意。

我的建议:将 SVG 直接放在带有超棒图标的 HTML 中:

Your benefit from this: all modern browsers support it without any limits like in img tags or as background image.

var divSvg = document.getElementById('svg'),
pics =
{
user: {col: '00a', icon: 'f007'},
home: {col: '08c', icon: 'f015'},
folder: {col: '88f', icon: 'f07c'},
gear: {col: '5a0', icon: 'f013'},
flag: {col: '05a', icon: 'f024'},
leaf: {col: '080', icon: 'f06c'}
},
svg =
'<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32">\
<text x="4" y="24" fill="COLOR" style="font:24px FontAwesome;cursor:pointer">PIC</text>\
</svg>';

for(var title in pics)
{
var newSVG = svg.replace('PIC', '&#x'+pics[title].icon+';');
//we put it in "B" tag to have a title because IE
//does not support title attribute and title tag in SVG
divSvg.innerHTML += '<b title="' + title + '">' +
newSVG.replace('COLOR', '#'+pics[title].col) + '</b>';
}

divSvg.onclick = function(e)
{
if(e.target.tagName == 'text')
{
document.getElementById('output').innerHTML = 'Was clicked on ' +
// we take title from "B" tag:
e.target.parentNode.parentNode.title;

/* if you need you can use:
switch(e.target.parentNode.parentNode.title)
{
case 'user': alert('Here some procedure with user');
case ... YOUR CODE
and so on... YOUR CODE
}*/
}
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet">
<div id="svg"></div><br>
<div id="output">Please click on any icon.</div>

关于javascript - 如何使用 Javascript 将 FontAwesome 渲染为 SVG 图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51196884/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com