在d3.js和SVG中使用Google字体 [英] Using google fonts with d3.js and SVG

查看:158
本文介绍了在d3.js和SVG中使用Google字体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Google字体中的自定义字体:

I'm trying to use a custom type face from google fonts:

<link href='http://fonts.googleapis.com/css?family=Karla|Quantico|Audiowide' rel='stylesheet' type='text/css'>

我将它们与此CSS一起用于普通文本:

I have used them with this css for normal text:

.customFont{
  font-family: 'Karla' ;
}

<h1 class="customFont"> My text </h1>

但是,当我尝试在SVG文本元素(例如图形中的节点文本)中使用d3.js添加这种类型的面孔时,它将删除我尝试添加到该类中的所有其他样式:

But when I try to add this type face with d3.js in SVG text elements (e.g. node text in a graph) it removes all other styling I try to add to the class:

.customFont {
  font-family: 'Karla' ;
  font-weight : bold;
  pointer-events: none;
  stroke:#fff;
  stroke-width:1px;
  fill-opacity: 1;
  fill: #000;
}

它将字体系列更改为自定义的Karla,但未保留所有其他属性.如何在一个类中获得新类型的face和其他属性?

it changes the font-family to the custom Karla but it doesn't keep all the other properties. How can I get the new type face and the other properties in one class?

推荐答案

我能够通过在我的SVG顶部的顶部添加<defs>标签并在其中添加<style type="text/css">标签来实现此目的.然后,您可以将文本添加到样式标签中,然后导入Google字体,如下所示:

I was able to accomplish this by adding an <defs> tag and appending a <style type="text/css"> tag within in that at the top of my SVG. You can then add text to the style tag and import your google fonts like so:

    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示例.剩下要做的就是将<text>标签放入SVG中,并对其应用适当的字体样式(字体系列,字体大小,字体粗细等):

I did this within an angular application I was working on, but that doesn't matter. This can be applied to any D3 example. All thats left to do is to take your <text> tags in your SVG and apply the appropriate font styles to them (font-family, font-size, font-weight, etc etc):

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');

希望这会有所帮助!

这篇关于在d3.js和SVG中使用Google字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆