制作网站的顺序,企业网站能个人备案吗,医院网站系统源码,做视频网站违法么!DOCTYPE html
html
bodyh1HTML5 Canvas 限定文本展示范围、自动计算缩放字体大小/h1div idtips0/div
div idcontent良田千顷不过一日三餐广厦万间只睡卧榻三尺良田千顷不过一日三餐…!DOCTYPE html
html
bodyh1HTML5 Canvas 限定文本展示范围、自动计算缩放字体大小/h1div idtips0/div
div idcontent良田千顷不过一日三餐广厦万间只睡卧榻三尺良田千顷不过一日三餐广厦万间只睡卧榻三尺良田千顷不过一日三餐广厦万间只睡卧榻三尺良田千顷不过一日三餐广厦万间只睡卧榻三尺卧尺卧尺厦厦万间只睡卧榻三尺卧尺卧尺万间只睡卧榻三尺良田千顷不过一日三餐广厦万间只睡卧榻三尺良田千顷不过一日三餐广厦万间只睡卧榻三尺良田千顷不过一日三餐广厦万间只睡卧榻三尺卧尺卧尺厦万间只睡卧榻三尺卧尺厦万榻三尺卧尺卧尺榻三间只睡三/divscript
// 默认字体16px最多一行显示18个字8行。
// 超出范围后自动缩小字体。let maxWidth 2304; // 合法最大宽度字体为16px、18个字、8行时的宽度
let minSize 10; // 限制最小字号支持缩到最小的字体大小let eleContent document.getElementById(content);
let eleTips document.getElementById(tips); // 将 eleTips 声明为全局变量
let content eleContent.innerText; // 获取文本内容let fontSize calculateFontSize(content, minSize, maxWidth);
eleContent.style.fontSize fontSize px; // 重设字号
eleTips.innerText 自适应字体大小: fontSize px;function calculateFontSize(text, minSize, maxWidth) {let fontSize 16; // 初始字体大小let currWidth 0;while (true) {const ctx document.createElement(canvas).getContext(2d);ctx.font fontSize px arial,sans-serif;currWidth ctx.measureText(text).width;//eleTips.innerText currWidth; // 在函数内部访问 eleTipsconsole.log(当前字号:fontSizepx当前宽度:currWidth偏差宽度:(currWidth-maxWidth));//console.log(currWidth)if (fontSize minSize || maxWidth currWidth) {break;}fontSize--;}return fontSize;
}/script
stylediv#content {width: 290px;height: 170px;border: 1px solid red;font: 16px arial, sans-serif;word-wrap: break-word;}
/style
/body
/html演示效果