css - 在 d3.js 和 SVG 中使用谷歌字体

标签 css svg d3.js

我正在尝试使用来自谷歌字体的自定义字体:

<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/

相关文章:

javascript - D 3's .call() returning "无法读取未定义的属性 'apply'”

javascript - 在 mouseover d3js 上更改 SVG 文本的文本

javascript - 并非所有坐标都使用平行坐标 (d3) 绘制

javascript - Velocity.js 和 calc() CSS 函数

html - 从单个 li 标签中删除一些东西

javascript - Svg scale() 不适用于 Edge(不是 Edge Chromium)

css - div 向两个方向倾斜

javascript - 当前用于将 html + svg + css 转换为 pdf 的库

css - 动态添加边框,增加高度

javascript - TR :hover won't trigger on invisible td