【发布时间】:2019-08-02 20:18:57
【问题描述】:
我正在尝试使用 JavaScript 将字体真棒图标动态添加到 svg 元素。
这是我的 SVG:
<svg id="mySVG" baseProfile="full" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMin" class="svg-map">
<g>
<circle id="test-1" cx="50" cy="50" r="10" fill="black" stroke="white" stroke-width="2"></circle>
<circle id="test-2" cx="150" cy="50" r="10" fill="black" stroke="white" stroke-width="2"></circle>
</g>
</svg>
然后我创建了一个函数来添加这样的文本元素:
var svgNS = "http://www.w3.org/2000/svg";
function createText(id, cx, cy, size, fill, stroke)
{
var seatX = document.createElementNS(svgNS,"text");
seatX.setAttributeNS(null,"id", id);
seatX.setAttributeNS(null,"x", cx);
seatX.setAttributeNS(null,"y", cy);
seatX.setAttributeNS(null,"r", size);
seatX.setAttributeNS(null,"fill", fill);
seatX.setAttributeNS(null,"stroke", stroke);
seatX.setAttributeNS(null,"font-family", 'FontAwesome Pro 5');
seatX.textContent = '';
document.getElementById("mySVG").appendChild(seatX);
}
$('circle').click(function () {
var id = $(this).attr('id');
var cx = parseInt($(this).attr('cx'));
var cy = parseInt($(this).attr('cy'))
var x = (cx - 8)
var y = (cy + 9.25)
createText(id+'_text', x, y, '10', 'white', 'none');
});
上面插入了新的文本元素,但是字体 awesome 显示为文本,而不是被转换。
如果我像这样手动添加文本元素,那么它可以工作:
<svg id="mySVG" baseProfile="full" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMin" class="svg-map">
<g>
<circle id="test-1" cx="50" cy="50" r="10" fill="black" stroke="white" stroke-width="2"></circle>
<circle id="test-2" cx="150" cy="50" r="10" fill="black" stroke="white" stroke-width="2"></circle>
<text id="test-1_text" x="42" y="59.25" r="10" fill="white" stroke="none" ></text>
</g>
</svg>
很明显,font awesome 不会加载到生成的新内容中。有没有办法解决这个问题?
【问题讨论】:
-
您使用的是哪个字体很棒的版本?尝试根据文档添加类。对于错误修复,请尝试找出您的 HTML 和 Javascript 变体之间的区别,可能是隐藏的伪元素。
-
我使用的是 Pro 5.6.3。完全没有区别。一个是动态加载的,一个不是。输出完全相同。
标签: javascript jquery dom svg font-awesome