我正在尝试使用来自谷歌字体的自定义字体:
<link href='http://fonts.googleapis.com/css?family=Karla|Quantico|Audiowide' rel='stylesheet' type='text/css'>
我将它们与此 css 一起用于普通文本:
.customFont{
font-family: 'Karla' ;
}
<h1 class="customFont"> My text </h1>
但是当我尝试在 SVG 文本元素(例如图中的节点文本)中使用 d3.js 添加这种类型时,它会删除我尝试添加到类中的所有其他样式:
.customFont {
font-family: 'Karla' ;
font-weight : bold;
pointer-events: none;
stroke:#fff;
stroke-width:1px;
fill-opacity: 1;
fill: #000;
}
它将字体系列更改为自定义 Karla,但不保留所有其他属性。如何在一个类中获取新字体和其他属性?
最佳答案
我能够通过添加 <defs>
来完成此操作标记并附加 <style type="text/css">
在我的 SVG 顶部的标签中。然后,您可以将文本添加到样式标签并像这样导入您的谷歌字体:
var root = d3.select(element)
.append('svg')
.attr('xmlns', 'http://www.w3.org/2000/svg')
.attr('xmlns:xmlns:xlink', 'http://www.w3.org/1999/xlink')
.attr('version', '1.1')
.attr('xml:space', 'preserve')
.attr('height', '100%')
.attr('width', '100%')
.attr('viewBox', '0 0 0 0');
root.append('defs')
.append('style')
.attr('type', 'text/css')
.text("@import url('https://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700,800');");
我在我正在处理的 Angular 应用程序中完成了此操作,但这并不重要。这可以应用于任何 D3 示例。剩下要做的就是带上你的<text>
在你的 SVG 中添加标签并为它们应用合适的字体样式(字体系列、字体大小、字体粗细等):
var svg = root.append('g').attr('class', 'root');
svg.append('text')
.text(scope.$parent.heading)
.attr('text-anchor', 'middle')
.style('font-size', '14px')
.style('font-family', '"Open Sans", sans-serif')
.style('font-weight', '500');
希望这对您有所帮助!
关于css - 在 d3.js 和 SVG 中使用谷歌字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21025876/