Programing

사용자의 브라우저가 표시 할 수있는 모든 글꼴 나열

lottogame 2020. 9. 25. 08:12
반응형

사용자의 브라우저가 표시 할 수있는 모든 글꼴 나열


브라우저가 표시 할 수있는 모든 글꼴 (또는 글꼴 계열)의 이름을 가져 오는 방법이 자바 스크립트에 있습니까? (사용자에게 사용 가능한 모든 글꼴 목록이있는 드롭 다운을 제공하고 사용자가 글꼴을 선택할 수 있도록하고 싶습니다.)이 목록을 미리 하드 코딩하거나 서버에서 보내지 않아도됩니다. (직관적으로 브라우저는 자신이 가지고있는 글꼴을 알아야하며 어떻게 든 자바 스크립트에 노출되어야합니다.)


자바 스크립트 버전은 약간 불안정합니다. 알려진 글꼴과 테스트를 반복하여 글꼴을 얻습니다.

가장 정확한 방법 (독점 플러그인을 사용해야하지만)은 Flash사용하는 것 입니다. 치수를 사용하여 개별적으로 테스트 할 필요없이 글꼴 목록을 가져올 수 있습니다.

일부 장치 (iDevices, Flash 플러그인이없는 브라우저 등)에서 작동하지 않는 대신 정확한 목록을 만들지 아니면 JavaScript를 통해서만 더 잘 지원 되는 부분 목록 을 가질 지 결정해야합니다 .


네, 있습니다! 저도이 질문을 사용하고 싶기 때문에이 질문을 해주셔서 감사합니다.

질문에 +1, 답변은 다음과 같습니다. :)

http://www.lalit.org/lab/javascript-css-font-detect

코드 에서 http://www.lalit.org/wordpress/wp-content/uploads/2008/05/fontdetect.js?ver=0.3

/**
 * 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;
};

요약

어떻게 작동합니까?

이 코드는 각 문자가 다른 글꼴에서 다르게 표시된다는 간단한 원칙에 따라 작동합니다. 따라서 다른 글꼴은 동일한 글꼴 크기의 동일한 문자열에 대해 다른 너비와 높이를 사용합니다.


<SCRIPT>
    function getFonts()
    {
        var nFontLen = dlgHelper.fonts.count;
        var rgFonts = new Array();
        for ( var i = 1; i < nFontLen + 1; i++ )
            rgFonts[i] = dlgHelper.fonts(i); 

        rgFonts.sort();
        for ( var j = 0; j < nFontLen; j++ )
            document.write( rgFonts[j] + "<BR>" );
    }
</SCRIPT>

<BODY onload="getFonts()">
<OBJECT id=dlgHelper CLASSID="clsid:3050f819-98b5-11cf-bb82-00aa00bdce0b" width="0px" height="0px">
</OBJECT>

In my search for this, I also found Font.js, which adds a Font object much like Image, so it's possible to check when a font is actually ready to use. Also works on installed/system fonts. Downside is IE9+ only due to needing Object.defineProperty (other browsers have it), but if you are doing modern web, this seems like an even better option. (I will, sadly, have to go with the answer above, upvoted and moving on for now. :))


I added two methods to Lalit Patel's Detector above :

  • addFont(family, stylesheetUrl, ruleString) -> detects if the font 'family' exists, if not adds a stylesheet loading the font using either stylesheetUrl if given or otherwise ruleString
  • addFontsArr(arr) -> adds an array of fonts

With this you can do:

fonts = [ 'Arial', 'Arial Black', { family: 'Lato', stylesheetUrl: 'https://fonts.googleapis.com/css?family=Lato'}, 'Leelawadee UI']
(new FontDetector()).addFontsArr(fonts);

code:

/**
 * 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');
 */
function FontDetector() {
    this.detect = detect;
    this.addFont = addFont;
    this.addFontsArr = addFontsArr;

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

    function addFont(family, stylesheetUrl, ruleString) {
        if (detect(family)) {
            //console.log('using internal font '+family);
            return true;
        }
        if (stylesheetUrl) {
            console.log('added stylesheet '+stylesheetUrl);
            var head = document.head, link = document.createElement('link');
            link.type = 'text/css';
            link.rel = 'stylesheet';
            link.href = stylesheetUrl;
            head.appendChild(link);
            return true;          
        }

        if (ruleString) {
            console.log('adding font rule:'+rule);
            var newStyle = document.createElement('style');
            newStyle.appendChild(document.createTextNode(rule));
            document.head.appendChild(newStyle);
            return true;
        }

        console.log('could not add font '+family);
    }

    function addFontsArr(arr) {
        arr.forEach(a => typeof a==='string' ? addFont(a) : addFont(a.family, a.stylesheetUrl, a.ruleString));
    }
};

Maybe this could be done in a completely different way, using a spritesheet with known font images for a specific character and comparing that with snapshots of a canvas element on which the same character is drawn with what the browser reports as the same font. The comparison may be done with something like resemble.js.

This is slower, but should also allow us to detect when the browser is lying.


Go to deviceinfo.me and click on the font detection button.

참고URL : https://stackoverflow.com/questions/3368837/list-every-font-a-users-browser-can-display

반응형