检测是否安装了特定字体

发布于 2024-09-02 13:43:54 字数 57 浏览 3 评论 0原文

如何仅使用 javascript 检测是否安装了特定字体。 (不管是否启用)。

谢谢

How to detect whether or not a particular font is installed using javascript only. (Disregard to whether it is enabled or not).

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

指尖微凉心微凉 2024-09-09 13:43:54

最后一个答案是11年前提供的。与此同时,对于仍在寻找解决方案的人来说,有新的解决方案可用:

您可以使用 FontFaceSet 浏览器提供的 API。目前它仍是一项实验性技术,但已在大多数浏览器(IE 除外)中可用。

来自 MDN Web 文档

FontFaceSet 的 check() 方法返回给定字体列表中的所有字体是否已加载且可用。

示例:

const fontAvailable = document.fonts.check("16px Arial");

使用 时check() 方法,请确保使用 ready 属性,加载完成后返回一个 Promise

let fontAvailable;
document.fonts.ready.then(() => {
    fontAvailable = document.fonts.check("16px Arial");
});

The last answer was provided 11 years ago. In the meantime there are new solutions available for people who are still looking for a solution:

You could use the FontFaceSet API provided by browsers. It is currently still an experimental technology, but already available in most browsers (except IE).

From MDN Web Docs

The check() method of the FontFaceSet returns whether all fonts in the given font list have been loaded and are available.

Example:

const fontAvailable = document.fonts.check("16px Arial");

When using the check() method, make sure to check if font loading operations have been completed by using the ready property, which returns a Promise when the loading has finished:

let fontAvailable;
document.fonts.ready.then(() => {
    fontAvailable = document.fonts.check("16px Arial");
});
无声静候 2024-09-09 13:43:54

对于最新的浏览器,window.queryLocalFonts()方法返回一个 Promise,该 Promise 满足表示本地可用字体的 FontData 对象数组。

对于较旧的浏览器,这里有一个解决方案来检查您的设备中的 html 页面是否安装了字体。
这个想法是:创建一个极窄的字体,并使用数据对象 url 在 css 中定义它,用该字体检查目标字体的宽度。

这是示例:

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
    <script type="text/javascript">
        (function () {
            const context = document.createElement("canvas").getContext("2d");
            context.font = "200px SANS-SERIF"
            const TEXT_TO_MEASURE = "A";
            var FONT_WIDTH = context.measureText(TEXT_TO_MEASURE).width;
            (function () {
                var style = document.createElement("style");
                style.setAttribute("type", "text/css");
                style.textContent = `@font-face{font-family:'__DEFAULT_FONT__';src:url('data:application/font-woff;base64,d09GRgABAAAAAAM0AAsAAAAABCQAAQAAAAAAAAAAAAAAAAAAAAAAAAAAABVPUy8yAAABcAAAADwAAABgNVxaOmNtYXAAAAG0AAAAKQAAADQADACUZ2FzcAAAAywAAAAIAAAACP//AANnbHlmAAAB6AAAACQAAAAwK9MKuGhlYWQAAAEIAAAAMwAAADYLo1XbaGhlYQAAATwAAAAcAAAAJP2RAdRobXR4AAABrAAAAAgAAAAIAMn9LGxvY2EAAAHgAAAABgAAAAYAGAAMbWF4cAAAAVgAAAAXAAAAIAAEAAVuYW1lAAACDAAAAQsAAAHwJKxCKHBvc3QAAAMYAAAAEwAAACD/KgCWeNpjYGRgYABi+QdqV+P5bb4ycHMwgMD1GraPEJqz/d80BoZ/PxgygFw2kFoGBgA++AvVAHjaY2BkYGBgBMOUf9MYc/79YACJIAMmAF7xBGN42mNgZGBgYGJgYQDRDFASCQAAAQEACgB42mNgZkhhnMDAysDAOovVmIGBURpCM19kSGMSYmBgAklhBR4+CgoMDgyOQMgIhhlgYUYoCaEZAIdLBiEAZP6WAGT+lnjaY2BgYGJgYGAGYhEgyQimWRgUgDQLEIL4jv//Q8j/B8B8BgBSlwadAAAAAAAADAAYAAB42mNg/DeNgeHfD4YMBmYGBkVTY9F/05IyMhgYcIgDAGnPDrV42oWQzU7CUBCFvwISZcEz3LjSBBoQ/yIrYzTEGEmIYY9QiglS01YMOx/DV+AtPXeophtjmumdOffMmXMH2GdOlaB2ACwUuzwQvi7yCk3d7PIqh794rcTZI+WryOslvMFn0OCJDW9EmjRhqtOxVRwJTXhXpxOa8CrOhJXQY0JhJ3Tocmn5NUt9jhEvxHKTk1kV6YyksNZ/ZnUsxaV0Uh4ZKm65YmycTL2J9J1UQ2l3/sT73JvKxlz0aJXc9Lkzds6NeiNNylWn1u37z0wjFP9UcSH8XFmbZ03JtYmFTu99Xqg4PqSR2Q5+9PxbnBx4Zyu9yP070+ultkPHoNhRmwchsaqpOLbhb0h9RfYAeNpjYGYAg//qDNMYsAAAKDQBwAAAAAAB//8AAg==');}`;
                document.documentElement.appendChild(style);
                var handleId = null;
                (function initailizeDefaultFont() {
                    context.font = "200px __DEFAULT_FONT__";
                    var width = context.measureText(TEXT_TO_MEASURE).width;
                    if (width != FONT_WIDTH) {
                        FONT_WIDTH = width;
                        cancelAnimationFrame(handleId);
                    }
                    else if (handleId == null) {
                        handleId = requestAnimationFrame(initailizeDefaultFont);
                    }

                })();
            })();
            function checkFontAvailable(font) {
                if (/^\s*SANS-SERIF\s*$/i.test(font)) {
                    return true;
                }
                if (!font || font == '__DEFAULT_FONT__') {
                    return false;
                }

                context.font = `200px ${font.replace(/^\s*['"]|['"]\s*$/g, "")}, __DEFAULT_FONT__`;

                var width = context.measureText(TEXT_TO_MEASURE).width;

                return width != FONT_WIDTH;
            }
            this.checkFontAvailable = checkFontAvailable;
        }).apply(this);

        console.log([checkFontAvailable("arial black b"), checkFontAvailable("arial black")]);
    </script>
</head>
<body>

</body>
</html>

这是测试结果:

checkFontAvailable("微软雅黑333")
false
checkFontAvailable("微软雅黑")
true
checkFontAvailable("arial")
true
checkFontAvailable("arial black")
true

For latest browser , the window.queryLocalFonts() method returns a Promise that fulfills with an array of FontData objects representing the font faces available locally.

for older browser, here is a solution to check if font is installed in your device in a html page.
The idea is :create a extreme narrow font and define it in css with data object url, check target font's width with this font.

Here is the example:

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
    <script type="text/javascript">
        (function () {
            const context = document.createElement("canvas").getContext("2d");
            context.font = "200px SANS-SERIF"
            const TEXT_TO_MEASURE = "A";
            var FONT_WIDTH = context.measureText(TEXT_TO_MEASURE).width;
            (function () {
                var style = document.createElement("style");
                style.setAttribute("type", "text/css");
                style.textContent = `@font-face{font-family:'__DEFAULT_FONT__';src:url('data:application/font-woff;base64,d09GRgABAAAAAAM0AAsAAAAABCQAAQAAAAAAAAAAAAAAAAAAAAAAAAAAABVPUy8yAAABcAAAADwAAABgNVxaOmNtYXAAAAG0AAAAKQAAADQADACUZ2FzcAAAAywAAAAIAAAACP//AANnbHlmAAAB6AAAACQAAAAwK9MKuGhlYWQAAAEIAAAAMwAAADYLo1XbaGhlYQAAATwAAAAcAAAAJP2RAdRobXR4AAABrAAAAAgAAAAIAMn9LGxvY2EAAAHgAAAABgAAAAYAGAAMbWF4cAAAAVgAAAAXAAAAIAAEAAVuYW1lAAACDAAAAQsAAAHwJKxCKHBvc3QAAAMYAAAAEwAAACD/KgCWeNpjYGRgYABi+QdqV+P5bb4ycHMwgMD1GraPEJqz/d80BoZ/PxgygFw2kFoGBgA++AvVAHjaY2BkYGBgBMOUf9MYc/79YACJIAMmAF7xBGN42mNgZGBgYGJgYQDRDFASCQAAAQEACgB42mNgZkhhnMDAysDAOovVmIGBURpCM19kSGMSYmBgAklhBR4+CgoMDgyOQMgIhhlgYUYoCaEZAIdLBiEAZP6WAGT+lnjaY2BgYGJgYGAGYhEgyQimWRgUgDQLEIL4jv//Q8j/B8B8BgBSlwadAAAAAAAADAAYAAB42mNg/DeNgeHfD4YMBmYGBkVTY9F/05IyMhgYcIgDAGnPDrV42oWQzU7CUBCFvwISZcEz3LjSBBoQ/yIrYzTEGEmIYY9QiglS01YMOx/DV+AtPXeophtjmumdOffMmXMH2GdOlaB2ACwUuzwQvi7yCk3d7PIqh794rcTZI+WryOslvMFn0OCJDW9EmjRhqtOxVRwJTXhXpxOa8CrOhJXQY0JhJ3Tocmn5NUt9jhEvxHKTk1kV6YyksNZ/ZnUsxaV0Uh4ZKm65YmycTL2J9J1UQ2l3/sT73JvKxlz0aJXc9Lkzds6NeiNNylWn1u37z0wjFP9UcSH8XFmbZ03JtYmFTu99Xqg4PqSR2Q5+9PxbnBx4Zyu9yP070+ultkPHoNhRmwchsaqpOLbhb0h9RfYAeNpjYGYAg//qDNMYsAAAKDQBwAAAAAAB//8AAg==');}`;
                document.documentElement.appendChild(style);
                var handleId = null;
                (function initailizeDefaultFont() {
                    context.font = "200px __DEFAULT_FONT__";
                    var width = context.measureText(TEXT_TO_MEASURE).width;
                    if (width != FONT_WIDTH) {
                        FONT_WIDTH = width;
                        cancelAnimationFrame(handleId);
                    }
                    else if (handleId == null) {
                        handleId = requestAnimationFrame(initailizeDefaultFont);
                    }

                })();
            })();
            function checkFontAvailable(font) {
                if (/^\s*SANS-SERIF\s*$/i.test(font)) {
                    return true;
                }
                if (!font || font == '__DEFAULT_FONT__') {
                    return false;
                }

                context.font = `200px ${font.replace(/^\s*['"]|['"]\s*$/g, "")}, __DEFAULT_FONT__`;

                var width = context.measureText(TEXT_TO_MEASURE).width;

                return width != FONT_WIDTH;
            }
            this.checkFontAvailable = checkFontAvailable;
        }).apply(this);

        console.log([checkFontAvailable("arial black b"), checkFontAvailable("arial black")]);
    </script>
</head>
<body>

</body>
</html>

Here is the test result:

checkFontAvailable("微软雅黑333")
false
checkFontAvailable("微软雅黑")
true
checkFontAvailable("arial")
true
checkFontAvailable("arial black")
true
べ映画 2024-09-09 13:43:54

将此代码放在 javascript 文件中的任意位置。

(function (document) {
    var width;
    var body = document.body;
  
    var container = document.createElement('span');
    container.innerHTML = Array(100).join('wi');
    container.style.cssText = [
      'position:absolute',
      'width:auto',
      'font-size:128px',
      'left:-99999px'
    ].join(' !important;');
  
    var getWidth = function (fontFamily) {
      container.style.fontFamily = fontFamily;
  
      body.appendChild(container);
      width = container.clientWidth;
      body.removeChild(container);
  
      return width;
    };
  
    // Pre compute the widths of monospace, serif & sans-serif
    // to improve performance.
    var monoWidth  = getWidth('monospace');
    var serifWidth = getWidth('serif');
    var sansWidth  = getWidth('sans-serif');
  
    window.isFontAvailable = function (font) {
      return monoWidth !== getWidth(font + ',monospace') ||
        sansWidth !== getWidth(font + ',sans-serif') ||
        serifWidth !== getWidth(font + ',serif');
    };
  })(document);

使用

console.log(isFontAvailable('Arial Black'))
// Evaluates true
console.log(isFontAvailable('thisdoesntexists'))
// Evaluates false

来源

https://www.samclarke.com/javascript-is-font-available< /a>

Put this code anywhere in your javascript file.

(function (document) {
    var width;
    var body = document.body;
  
    var container = document.createElement('span');
    container.innerHTML = Array(100).join('wi');
    container.style.cssText = [
      'position:absolute',
      'width:auto',
      'font-size:128px',
      'left:-99999px'
    ].join(' !important;');
  
    var getWidth = function (fontFamily) {
      container.style.fontFamily = fontFamily;
  
      body.appendChild(container);
      width = container.clientWidth;
      body.removeChild(container);
  
      return width;
    };
  
    // Pre compute the widths of monospace, serif & sans-serif
    // to improve performance.
    var monoWidth  = getWidth('monospace');
    var serifWidth = getWidth('serif');
    var sansWidth  = getWidth('sans-serif');
  
    window.isFontAvailable = function (font) {
      return monoWidth !== getWidth(font + ',monospace') ||
        sansWidth !== getWidth(font + ',sans-serif') ||
        serifWidth !== getWidth(font + ',serif');
    };
  })(document);

Usage

console.log(isFontAvailable('Arial Black'))
// Evaluates true
console.log(isFontAvailable('thisdoesntexists'))
// Evaluates false

Source

https://www.samclarke.com/javascript-is-font-available

執念 2024-09-09 13:43:54

@Matchu 正确地建议了您,但这就是您正在寻找的内容:

http://remysharp.com/2008/07/08/how-to-detect-if-a-font-is-installed-only-using-javascript/< /a>

@Matchu suggested you rightly but here is what you are looking for:

http://remysharp.com/2008/07/08/how-to-detect-if-a-font-is-installed-only-using-javascript/

↙温凉少女 2024-09-09 13:43:54

如果您绝对需要特定字体,则所有访问者都必须拥有最新的浏览器。然后你就可以使用网络字体了。

如果这不是一个选项,您必须在服务器上渲染字体并提供图像。

If you absolutely need a specific font, all your visitors must have current browsers. Then you can use webfonts.

If that's not an option, you must render the font on your server and serve an image.

小姐丶请自重 2024-09-09 13:43:54

字体系列声明应该足以在您要使用的字体不存在时提供后备。

但是,如果您确实需要在网站中使用特殊字体,尽管这使用 JavaScript,但我建议您使用 Cufon< /a> 因为它是最跨浏览器的解决方案 - 有一个 CSS3 修复(字体声明),但它还不能在所有浏览器中工作。

Font family declarations should suffice to provide a fallback in case the font you want to use is not present.

But if you really need to use a special font in your site, although this uses JavaScript, I'd recommend Cufon since it's the most cross-browser solution out there - there is a CSS3 fix (font-face declarations), but it doesn't work in all browsers yet.

八巷 2024-09-09 13:43:54

您是否可以像世界其他地方一样:使用 CSS 指定字体,并提供后备方案?任何应用程序都不应该需要知道可用的字体,也没有可靠的方法来做到这一点。 (您可能必须使用字体打印隐藏的 div 并测量它以查看尺寸是否符合您的预期,但这会非常脆弱。)

只需:

body { font-family: MyFont, Helvetica, Arial, sans-serif }

如果您想对除显示之外的字体进行任何操作如果可能的话,请考虑替代解决方案。

How about you just do what the rest of the world does: specify the font with CSS, and offer fallbacks? No app should ever need to know what fonts are available, nor is there a reliable way of doing so. (You would probably have to print hidden div with the font and measure it to see if the dimensions are what you expected, but that would be extremely brittle.)

Just go for:

body { font-family: MyFont, Helvetica, Arial, sans-serif }

If you want to be doing anything with the font other than display things in it if possible, consider an alternative solution.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文