久しぶりの更新ですね。
色々あったのですが、それは後ほど書くとして...
とあるサイトを作ってたのですが、明朝体系のフォントを使用する必要があって、制作も完了してめでたしめでたし、と思ってたらとあるPCで見るとフォントがゴシック系になってるではありませんか。
特殊ではないフォントだったので油断してたのですが、PCによってはインストールされてない可能性があったみたいです。
それで一番問題だったのは、使用したいフォントと代替フォントのデフォルトのフォントサイズが違いすぎるというという点です。
対処する為にはデフォルトのフォントが入っているかどうかを判別して、ない場合はcssでフォントサイズを変えるといった処理です。
で、その時の対処方法です。
PHPSPOTさんで紹介されていた「JavaScriptでマシンに特定のフォントがインストールされているか知る方法。」で紹介されているサイトを元に以下のように対処しました。
<script type="text/javascript">
/**
* Actual function that does all the work. Returns an array with all the info.
* My Assumption is that most of the browsers will have arial set as their default sans-serif font.
*/
var Detector = function(){
var h = document.getElementsByTagName("BODY")[0];
var d = document.createElement("DIV");
var s = document.createElement("SPAN");
d.appendChild(s);
d.style.fontFamily = "serif"; //font for the parent element DIV.
s.style.fontFamily = "serif"; //have to use serif coz in FF3.0, it doesn't fall back to font of parent element.
s.style.fontSize = "72px"; //we test using 72px font size, we may use any size. I guess larger the better.
s.innerHTML = "mmmmmmmmmml"; //we use m or w because these two characters take up the maximum width. And we use a L so that the same matching fonts can get separated
h.appendChild(d);
var defaultWidth = s.offsetWidth; //now we have the defaultWidth
var defaultHeight = s.offsetHeight; //and the defaultHeight, we compare other fonts with these.
h.removeChild(d);
/* test
* params:
* font - name of the font you wish to detect
* return:
* f[0] - Input font name.
* f[1] - Computed width.
* f[2] - Computed height.
* f[3] - Detected? (true/false).
*/
function debug(font) {
h.appendChild(d);
var f = [];
f[0] = s.style.fontFamily = font; // Name of the font
f[1] = s.offsetWidth; // Width
f[2] = s.offsetHeight; // Height
h.removeChild(d);
font = font.toLowerCase();
if (font == "serif") {
f[3] = true; // to set arial and sans-serif true
} else {
f[3] = (f[1] != defaultWidth || f[2] != defaultHeight); // Detected?
}
return f;
}
function test(font){
f = debug(font);
return f[3];
}
this.detailedTest = debug;
this.test = test;
}
var fonts = [];
/**
* other stuff
*/
var detective = new Detector();
if(detective.test('ここに判別したいフォント') == true){
}
else{
document.write('<link rel="stylesheet" href="hoge.css" type="text/css" />');
}
</script>
こんな感じで判別できます。
ただ、document.writeでcssを読み込むというのはスマートではないのでjavascriptからcssを読み込むといった対応を行えばスマートだと思います。
フォントのインストール判別ができれば、できる事の幅が広がりそうです。



Leave a comment