指定したフォントがインストールされているか確認する - JavaScript

JavaScriptを利用して、指定したフォントがインストールされているか確認するコードを紹介します。

概要

http://www.lalit.org/lab/javascript-css-font-detect/のライブラリを用いると、インストールの有無を確認できます。

コード

以下のコードを記述します。

index.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>

  <script type="text/javascript" src="fontdetect.js"></script>
  <script type="text/javascript">
    window.onload = function () {
      var detective = new Detector();
      if (detective.detect('AR丸ゴシック体M04') == true) {
        target = document.getElementById("message");
        target.innerHTML = "「AR丸ゴシック体M04」はインストールされています。";
      } else {
        target = document.getElementById("message");
        target.innerHTML = "「AR丸ゴシック体M04」はインストールされていません。";
      }
    };
  </script>

</head>
<body>
  <div id="message"></div>
</body>
</html>

fontdetect.js

fontdetect.jsはhttp://www.lalit.org/lab/javascript-css-font-detect/からダウンロードできます。

/**
 * JavaScript code to detect available availability of a
 * particular font in a browser using JavaScript and CSS.
 *
 * Author : Lalit Patel
 * Website: http://www.lalit.org/lab/javascript-css-font-detect/
 * License: Apache Software License 2.0
 *          http://www.apache.org/licenses/LICENSE-2.0
 * Version: 0.15 (21 Sep 2009)
 *          Changed comparision font to default from sans-default-default,
 *          as in FF3.0 font of child element didn't fallback
 *          to parent element if the font is missing.
 * Version: 0.2 (04 Mar 2012)
 *          Comparing font against all the 3 generic font families ie,
 *          'monospace', 'sans-serif' and 'sans'. If it doesn't match all 3
 *          then that font is 100% not available in the system
 * Version: 0.3 (24 Mar 2012)
 *          Replaced sans with serif in the list of baseFonts
 */

/**
 * Usage: d = new Detector();
 *        d.detect('font name');
 */
var Detector = function() {
    // a font will be compared against all the three default fonts.
    // and if it doesn't match all 3 then that font is not available.
    var baseFonts = ['monospace', 'sans-serif', 'serif'];

    //we use m or w because these two characters take up the maximum width.
    // And we use a LLi so that the same matching fonts can get separated
    var testString = "mmmmmmmmmmlli";

    //we test using 72px font size, we may use any size. I guess larger the better.
    var testSize = '72px';

    var h = document.getElementsByTagName("body")[0];

    // create a SPAN in the document to get the width of the text we use to test
    var s = document.createElement("span");
    s.style.fontSize = testSize;
    s.innerHTML = testString;
    var defaultWidth = {};
    var defaultHeight = {};
    for (var index in baseFonts) {
        //get the default width for the three base fonts
        s.style.fontFamily = baseFonts[index];
        h.appendChild(s);
        defaultWidth[baseFonts[index]] = s.offsetWidth; //width for the default font
        defaultHeight[baseFonts[index]] = s.offsetHeight; //height for the defualt font
        h.removeChild(s);
    }

    function detect(font) {
        var detected = false;
        for (var index in baseFonts) {
            s.style.fontFamily = font + ',' + baseFonts[index]; // name of the font along with the base font for fallback.
            h.appendChild(s);
            var matched = (s.offsetWidth != defaultWidth[baseFonts[index]] || s.offsetHeight != defaultHeight[baseFonts[index]]);
            h.removeChild(s);
            detected = detected || matched;
        }
        return detected;
    }

    this.detect = detect;
};

解説

デフォルトのフォントを用いてテスト文字列"mmmmmmmmmmlli"の幅と高さを取得します。このコードではデフォルトのフォントとして、'monospace', 'sans-serif', 'serif'の3つを利用しています。次に、指定したフォントを用いてテスト文字列"mmmmmmmmmmlli"の幅と高さを取得します。取得した文字列の幅と高さが、3つのデフォルトフォントでのテスト文字列の幅と高さにいずれも一致しなかった場合、指定したフォントはデフォルトのフォントではないため、フォントはインストールされていると判定します。デフォルトのフォントの幅と高さに一致した場合は、フォントが存在しないためデフォルトのフォントが代用されたとみなし、フォントはインストールされていないと判定します。

実行結果

「AR丸ゴシック体M04」がインストールされているマシンのWebブラウザでindex.htmlファイルにアクセスします。フォントがインストールされている旨のメッセージが表示されます。


別の「AR丸ゴシック体M04」がインストールされていないマシンのWebブラウザで同じファイルにアクセスした場合は、インストールされていない旨のメッセージが表示されます。


著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2015-04-08
作成日: 2015-04-07
iPentec all rights reserverd.