菜单

ABlog

Github
文章漫游 切换到深色模式 切换到浅色模式
/**
 * 判断浏览器是否支持字体
 * @param {string} font 字体名称
 * @returns {boolean} 是否支持
 * @example
 * const flag = isSupportFontFamily('微软雅黑')
 * if(flag) console.log('支持微软雅黑字体')
 * else console.log('不支持微软雅黑字体')
 */
function isSupportFontFamily(font) {
  const defaultFont = "Arial";
  if (font.toLowerCase() == defaultFont.toLowerCase()) return true;
  const character = "a";
  const fontSize = 100;
  const width = 100;
  const height = 100;
  const canvas = document.createElement("canvas");
  const context = canvas.getContext("2d", { willReadFrequently: true });
  canvas.width = width;
  canvas.height = height;
  context.textAlign = "center";
  context.fillStyle = "black";
  context.textBaseline = "middle";
  const drawFont = (font) => {
    context.clearRect(0, 0, width, height);
    context.font = fontSize + "px " + font + ", " + defaultFont;
    context.fillText(character, width / 2, height / 2);
    const imageData = context.getImageData(0, 0, width, height).data;
    return Array.from(imageData).filter((element) => element != 0);
  };
  return drawFont(defaultFont).join("") !== drawFont(font).join("");
}