在JavaScript中有没有一种方法可以获取浏览器能够显示的所有字体(或字体系列)的名称?(我想给用户一个下拉菜单,列出所有可用的字体,并允许用户选择一个字体。)我不想预先硬编码此列表或从服务器发送它。(直观地看,浏览器应该知道它拥有哪些字体,并且这应该以某种方式暴露给JavaScript。)
在JavaScript中有没有一种方法可以获取浏览器能够显示的所有字体(或字体系列)的名称?(我想给用户一个下拉菜单,列出所有可用的字体,并允许用户选择一个字体。)我不想预先硬编码此列表或从服务器发送它。(直观地看,浏览器应该知道它拥有哪些字体,并且这应该以某种方式暴露给JavaScript。)
有的!我很高兴你问了这个问题,因为现在我也想用它。
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;
};
概述
它是如何工作的?
这段代码基于一个简单的原理,即每个字符在不同的字体中显示不同。因此,对于相同字号的相同字符字符串,不同字体将采用不同的宽度和高度。
'Arial',
'Arial Black',
'Bahnschrift',
'Calibri',
'Cambria',
'Cambria Math',
'Candara',
'Comic Sans MS',
'Consolas',
'Constantia',
'Corbel',
'Courier New',
'Ebrima',
'Franklin Gothic Medium',
'Gabriola',
'Gadugi',
'Georgia',
'HoloLens MDL2 Assets',
'Impact',
'Ink Free',
'Javanese Text',
'Leelawadee UI',
'Lucida Console',
'Lucida Sans Unicode',
'Malgun Gothic',
'Marlett',
'Microsoft Himalaya',
'Microsoft JhengHei',
'Microsoft New Tai Lue',
'Microsoft PhagsPa',
'Microsoft Sans Serif',
'Microsoft Tai Le',
'Microsoft YaHei',
'Microsoft Yi Baiti',
'MingLiU-ExtB',
'Mongolian Baiti',
'MS Gothic',
'MV Boli',
'Myanmar Text',
'Nirmala UI',
'Palatino Linotype',
'Segoe MDL2 Assets',
'Segoe Print',
'Segoe Script',
'Segoe UI',
'Segoe UI Historic',
'Segoe UI Emoji',
'Segoe UI Symbol',
'SimSun',
'Sitka',
'Sylfaen',
'Symbol',
'Tahoma',
'Times New Roman',
'Trebuchet MS',
'Verdana',
'Webdings',
'Wingdings',
'Yu Gothic',
'American Typewriter',
'Andale Mono',
'Arial',
'Arial Black',
'Arial Narrow',
'Arial Rounded MT Bold',
'Arial Unicode MS',
'Avenir',
'Avenir Next',
'Avenir Next Condensed',
'Baskerville',
'Big Caslon',
'Bodoni 72',
'Bodoni 72 Oldstyle',
'Bodoni 72 Smallcaps',
'Bradley Hand',
'Brush Script MT',
'Chalkboard',
'Chalkboard SE',
'Chalkduster',
'Charter',
'Cochin',
'Comic Sans MS',
'Copperplate',
'Courier',
'Courier New',
'Didot',
'DIN Alternate',
'DIN Condensed',
'Futura',
'Geneva',
'Georgia',
'Gill Sans',
'Helvetica',
'Helvetica Neue',
'Herculanum',
'Hoefler Text',
'Impact',
'Lucida Grande',
'Luminari',
'Marker Felt',
'Menlo',
'Microsoft Sans Serif',
'Monaco',
'Noteworthy',
'Optima',
'Palatino',
'Papyrus',
'Phosphate',
'Rockwell',
'Savoye LET',
'SignPainter',
'Skia',
'Snell Roundhand',
'Tahoma',
'Times',
'Times New Roman',
'Trattatello',
'Trebuchet MS',
'Verdana',
'Zapfino',
const fontCheck = new Set([
// Windows 10
'Arial', 'Arial Black', 'Bahnschrift', 'Calibri', 'Cambria', 'Cambria Math', 'Candara', 'Comic Sans MS', 'Consolas', 'Constantia', 'Corbel', 'Courier New', 'Ebrima', 'Franklin Gothic Medium', 'Gabriola', 'Gadugi', 'Georgia', 'HoloLens MDL2 Assets', 'Impact', 'Ink Free', 'Javanese Text', 'Leelawadee UI', 'Lucida Console', 'Lucida Sans Unicode', 'Malgun Gothic', 'Marlett', 'Microsoft Himalaya', 'Microsoft JhengHei', 'Microsoft New Tai Lue', 'Microsoft PhagsPa', 'Microsoft Sans Serif', 'Microsoft Tai Le', 'Microsoft YaHei', 'Microsoft Yi Baiti', 'MingLiU-ExtB', 'Mongolian Baiti', 'MS Gothic', 'MV Boli', 'Myanmar Text', 'Nirmala UI', 'Palatino Linotype', 'Segoe MDL2 Assets', 'Segoe Print', 'Segoe Script', 'Segoe UI', 'Segoe UI Historic', 'Segoe UI Emoji', 'Segoe UI Symbol', 'SimSun', 'Sitka', 'Sylfaen', 'Symbol', 'Tahoma', 'Times New Roman', 'Trebuchet MS', 'Verdana', 'Webdings', 'Wingdings', 'Yu Gothic',
// macOS
'American Typewriter', 'Andale Mono', 'Arial', 'Arial Black', 'Arial Narrow', 'Arial Rounded MT Bold', 'Arial Unicode MS', 'Avenir', 'Avenir Next', 'Avenir Next Condensed', 'Baskerville', 'Big Caslon', 'Bodoni 72', 'Bodoni 72 Oldstyle', 'Bodoni 72 Smallcaps', 'Bradley Hand', 'Brush Script MT', 'Chalkboard', 'Chalkboard SE', 'Chalkduster', 'Charter', 'Cochin', 'Comic Sans MS', 'Copperplate', 'Courier', 'Courier New', 'Didot', 'DIN Alternate', 'DIN Condensed', 'Futura', 'Geneva', 'Georgia', 'Gill Sans', 'Helvetica', 'Helvetica Neue', 'Herculanum', 'Hoefler Text', 'Impact', 'Lucida Grande', 'Luminari', 'Marker Felt', 'Menlo', 'Microsoft Sans Serif', 'Monaco', 'Noteworthy', 'Optima', 'Palatino', 'Papyrus', 'Phosphate', 'Rockwell', 'Savoye LET', 'SignPainter', 'Skia', 'Snell Roundhand', 'Tahoma', 'Times', 'Times New Roman', 'Trattatello', 'Trebuchet MS', 'Verdana', 'Zapfino',
].sort());
(async() => {
await document.fonts.ready;
const fontAvailable = new Set();
for (const font of fontCheck.values()) {
if (document.fonts.check(`12px "${font}"`)) {
fontAvailable.add(font);
}
}
console.log('Available Fonts:', [...fontAvailable.values()]);
})();
fonts.check
只在Chrome上有效 - 标准情况下,如果字体不可用,fonts.check()
也应该返回true,参考来源:https://developer.mozilla.org/en-US/docs/Web/API/FontFaceSet/check。我检查了一下,在Safari中,它也会为您传递的任何虚构字体返回`true`。 - olivarra1有一种方法可以使用 document.fonts
来实现这个。
返回的值是文档的 FontFaceSet 接口。FontFaceSet 接口对于加载新字体、检查先前加载字体的状态等非常有用。
function listFonts() {
return [...document.fonts.values()];
}
function listFontFamilies() {
const fontFaces = [...document.fonts.values()];
const families = fontFaces.map(font => font.family);
// converted to set then to array to remove duplicates
return [...new Set(families)];
}
listFonts() {
let fonts = document['fonts'];
const it = fonts.entries();
let arr = [];
let done = false;
while (!done) {
const font = it.next();
if (!font.done) {
arr.push(font.value[0].family);
} else {
done = font.done;
}
}
// 转换为集合再转回数组以过滤重复值
return [...new Set(arr)];
}
- rufreakdeJavaScript版本有些不稳定。它通过遍历已知的字体并进行测试来获取字体。
最准确的方法(虽然需要使用专有插件)是使用Flash。在这里,您可以获取字体列表,而无需使用尺寸逐个测试字体。
你将需要决定是为了得到精确列表而牺牲一些设备的支持(iDevices、没有Flash插件的浏览器等),还是仅通过JavaScript获得更好支持的部分列表。
console.log(await queryLocalFonts());
您也可以检查用户是否已授予权限:
const {state} = await navigator.permissions.query({name: 'local-fonts'});
console.log(state); // Either 'granted', 'prompt' or 'denied'
const pickedFonts = await navigator.fonts.query()
访问它,并且您可以通过for (const metadata of pickedFonts) { }
迭代其选定的选项。相应地,文章已进行更新。 - DenverCoder9字体访问API在Chrome 87中可用:
// Query for all available fonts and log metadata.
const fonts = navigator.fonts.query();
try {
for await (const metadata of fonts) {
console.log(`${metadata.family} (${metadata.fullName})`);
}
} catch (err) {
console.error(err);
}
// Roboto (Roboto Black)
// Roboto (Roboto Black Italic)
// Roboto (Roboto Bold)
更多信息请点击这里
使用此可以做到:
fonts = [ 'Arial', 'Arial Black', { family: 'Lato', stylesheetUrl: 'https://fonts.googleapis.com/css?family=Lato'}, 'Leelawadee UI']
(new FontDetector()).addFontsArr(fonts);
代码:
/**
* 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));
}
};
<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>
Object.defineProperty
(其他浏览器都支持),但如果您正在进行现代网页设计,这似乎是更好的选择。(很遗憾,我将暂时接受上面的答案并进行投票。 :))