我正在尝试使用谷歌字体的自定义脸型:
<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;
}
它将font-family更改为自定义Karla,但它不保留所有其他属性。如何在一个类中获取新类型的face和其他属性?
答案 0 :(得分:1)
我能够通过添加<defs>
标记并在我的SVG顶部添加<style type="text/css">
标记来实现此目的。然后,您可以在样式标记中添加文本并导入您的Google字体,如下所示:
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');");
我是在我正在进行的一个有角度的应用程序中完成的,但这并不重要。这可以应用于任何D3示例。剩下要做的就是在你的SVG中使用<text>
标签并对它们应用适当的字体样式(font-family,font-size,font-weight等等):
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');
希望这有帮助!
答案 1 :(得分:0)
看起来问题与未设置font-size有关。字体大小在&lt;中的默认值不同。文字&gt;元素然后是一个HTML元素。如果您尝试将外观从html元素(在您的情况下为&lt; h1&gt;)复制到&lt;中,则可能不需要设置填充笔划。文字&gt;元件。
<html>
<head>
<link href='http://fonts.googleapis.com/css?family=Karla|Quantico|Audiowide' rel='stylesheet' type='text/css'>
<style>
.customFont {
font-family: 'Karla' ;
font-weight : bold;
pointer-events: none;
stroke:#fff;
stroke-width:1px;
fill-opacity: 1;
fill: #000;
}
.customFont1 {
font-family: 'Karla';
font-size: 28px;
font-weight : bold;
pointer-events: none;
fill-opacity: 1;
fill: #000;
}
</style>
</head>
<body>
<h1 class="customFont"> My text </h1>
<h1 class="customFont1"> My text </h1>
<div>
<svg>
<g>
<text x="0" y="20" class="customFont">My text</text>
</g>
<g>
<text x="0" y="50" class="customFont1">My text</text>
</g>
</svg>
</div>
</html>
这是一个显示一些比较的jsfiddle。
它不包含d3,但它确实使用svg,这最终是d3创建的。
答案 2 :(得分:0)
只需在链接中添加
<head>
href="https://fonts.googleapis.com/css?family=Roboto+Condensed&display=swap" rel="stylesheet">
</head>
接下来,只需添加CSS。
.axis text {
fill: #2b2929;
font-family: 'Roboto Condensed';
font-size: 120%;
}
对我有用。