js实现字体
字体样式设置
在JavaScript中,可以通过操作DOM元素的style属性来动态修改字体样式。常见的字体相关属性包括:
fontFamily: 设置字体类型(如"Arial", "Times New Roman")fontSize: 设置字体大小(如"16px", "1.2em")fontWeight: 设置字体粗细(如"normal", "bold")fontStyle: 设置字体风格(如"normal", "italic")
// 获取元素并设置字体样式
const element = document.getElementById('textElement');
element.style.fontFamily = 'Arial, sans-serif';
element.style.fontSize = '18px';
element.style.fontWeight = 'bold';
动态加载网络字体
通过JavaScript可以动态加载Google Fonts等网络字体资源:

// 创建link元素加载Google字体
const link = document.createElement('link');
link.href = 'https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap';
link.rel = 'stylesheet';
document.head.appendChild(link);
// 使用加载的字体
document.body.style.fontFamily = 'Roboto, sans-serif';
Canvas文字渲染
在Canvas中绘制文字时,需要设置字体属性:
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.font = 'italic 700 24px "Times New Roman"';
ctx.fillText('Hello World', 50, 50);
SVG文字处理
通过JavaScript操作SVG文字元素:

const svg = document.getElementById('svgContainer');
const text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
text.setAttribute('x', '20');
text.setAttribute('y', '30');
text.setAttribute('font-family', 'Verdana');
text.setAttribute('font-size', '20');
text.textContent = 'SVG Text';
svg.appendChild(text);
响应式字体调整
根据窗口大小动态调整字体大小:
function adjustFontSize() {
const baseSize = 16;
const scale = window.innerWidth / 1200;
const newSize = Math.max(12, Math.min(baseSize * scale, 24));
document.documentElement.style.fontSize = `${newSize}px`;
}
window.addEventListener('resize', adjustFontSize);
adjustFontSize();
字体检测
检测浏览器是否支持特定字体:
function isFontAvailable(fontName) {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
ctx.font = '72px monospace';
const defaultWidth = ctx.measureText('mmmmmmmmmm').width;
ctx.font = `72px "${fontName}", monospace`;
return ctx.measureText('mmmmmmmmmm').width !== defaultWidth;
}






