LoginSignup
12
15

More than 5 years have passed since last update.

SVG から Webfont を生成する

Last updated at Posted at 2016-01-28

はじめに

Web 上でアイコンの色を動的に変えたかったので、Webfont を使うことにした。

最初は SVG 画像を使っていたが、色の変更やサイズの変更、ロード時の画像サイズなど色々と面倒が多かったので Webfont 化することに。

(もしかしたら object タグで使っていたから不都合があっただけなのかも…)

HTTPリクエストを減らすために【WebFont編】ドラッグ&ドロップしてコマンド叩いてウェーイ

上記URLを参考に、grunt-webfont でやることに。

準備

まずは必要なものをインストール
※ node はすでにインストールされているものとする

$ brew instal ttfautohint fontforge --with-python

適当に変換用のディレクトリを作成

$ mkdir ~/Desktop/SvgToWebfont
$ cd ~/Desktop/SvgToWebfont

次に package.json を用意する

package.json
{
  "name": "SvgToWebfont",
  "version": "0.0.1",
  "description": "Convert SVG file to Webfont",
  "main": "Gruntfile.js",
  "devDependencies": {
    "grunt": "^0.4.5",
    "grunt-webfont": "^0.4.8"
  }
}

パッケージをインストール

$ npm install

そして Gruntfile.js を作成。

Gruntfile.js
module.exports = function(grunt) {
  grunt.loadNpmTasks('grunt-webfont');

  grunt.initConfig ({
    pkg: grunt.file.readJSON('package.json'),
    webfont: {
      icons: {
        src: 'icons/*.svg',
        dest: 'build/fonts'
      }
    }
  });

  grunt.registerTask('default', ['webfont']);
}

変換

ディレクトリ構造はこんな感じ

SvgToWebfont
├── build
│   └── fonts
├── icons
└── node_modules

grunt を実行する

$ grunt

と、build/fonts 配下にファイルが出力される。

build/fonts
├── icons.css
├── icons.eot
├── icons.html
├── icons.svg
├── icons.ttf
└── icons.woff

使う

build/fonts をまるごとコピって使うだけ。
使うときは build/fonts ディレクトリをまるごとコピーして、icons.css だけ読みこめば OK。

<link rel="stylesheet" href="{{your path}}/icons.css"></link>

ちなみに、icons.html ファイルを開くと、アイコンの一覧とか Webfont を使うためのクラス名が書いてあるページができる。

icons.png

これを参考に

<body>
  <i class="icon icon_hoge"></i>
</body>

と書けばアイコンを使える。

所管

  • Webfont なので複数の色を持ったものや複雑なものには向かないが、サイズや色を変更できるので好き
  • nodejs で動いているので、watch させておいてサーバにアップロードしたら自動で更新とかすれば便利かも
    • わざわざエンジニアがコマンド打たなくてもデザイナーに直接実行してもらえて便利
  • icon icon_hogeicon 部分は好きに変更できるが、それはまた別の機会に
12
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
15