JavaScript를 사용하여 웹 브라우저의 렌더링 엔진에서 사용할 수 있는 글꼴을 열거하는 방법은 무엇입니까?

Mary-Kate Olsen
풀어 주다: 2024-10-23 13:44:01
원래의
941명이 탐색했습니다.

How to Enumerate Fonts Available to a Web Browser's Rendering Engine using JavaScript?

웹 브라우저의 렌더링 엔진에서 사용할 수 있는 글꼴 열거

웹 개발에서는 사용자에게 사용자 정의 가능한 탐색 환경을 제공하는 것이 바람직한 경우가 많습니다. 여기에는 브라우저가 렌더링할 수 있는 글꼴 목록에서 원하는 글꼴을 선택하도록 허용하는 것이 포함될 수 있습니다. 이를 용이하게 하려면 사용 가능한 모든 글꼴 목록을 프로그래밍 방식으로 얻을 수 있는 방법이 필요합니다.

이 문제를 해결하는 한 가지 접근 방식은 글꼴 목록을 하드코딩하거나 서버에서 검색하는 것입니다. 그러나 이 접근 방식은 번거로울 수 있으며 사용자가 브라우저에 추가 글꼴을 설치한 상황에는 적합하지 않을 수 있습니다.

다행히도 JavaScript를 사용하는 더 우아하고 동적인 솔루션이 있습니다. 다음 스니펫은 글꼴 감지라는 기술을 활용합니다.

<code class="js">/**
 * 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 = &quot;mmmmmmmmmmlli&quot;;

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

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

    // create a SPAN in the document to get the width of the text we use to test
    var s = document.createElement(&quot;span&quot;);
    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;
};</code>
로그인 후 복사

이 코드는 'Detector' 메소드를 사용하여 'Detector' 개체를 생성합니다. 'Detect' 메소드는 글꼴 이름을 인수로 사용하고 브라우저에서 글꼴을 렌더링할 수 있는지 여부를 나타내는 부울 값을 반환합니다.

코드는 요소 및 해당 글꼴 모음을 지정된 글꼴로 설정합니다. 그러면 이 요소가 문서 본문에 추가됩니다. 그런 다음 요소의 너비와 높이를 측정하고 세 가지 'monospace', 'sans-serif' 및 'serif' 글꼴의 기본값과 비교합니다. 측정된 값이 기본값과 다른 경우 지정된 글꼴을 사용할 수 있음을 나타냅니다.

사용 가능한 모든 글꼴을 열거하려면 글꼴 이름 배열을 반복하고 각 글꼴에 대해 '감지' 메소드를 호출하면 됩니다. . 결과는 브라우저가 렌더링할 수 있는 모든 글꼴 목록이 됩니다.

위 내용은 JavaScript를 사용하여 웹 브라우저의 렌더링 엔진에서 사용할 수 있는 글꼴을 열거하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!