HTML5 Canvas 限定文本区域大小,文字自动换行,自动缩放

复制代码
<!DOCTYPE html>
<html>
<body>

<h1>HTML5 Canvas 限定文本展示范围、自动计算缩放字体大小</h1>

<div id="tips">0</div>
<div id="content">良田千顷不过一日三餐广厦万间只睡卧榻三尺良田千顷不过一日三餐广厦万间只睡卧榻三尺良田千顷不过一日三餐广厦万间只睡卧榻三尺良田千顷不过一日三餐广厦万间只睡卧榻三尺卧尺卧尺厦厦万间只睡卧榻三尺卧尺卧尺万间只睡卧榻三尺良田千顷不过一日三餐广厦万间只睡卧榻三尺良田千顷不过一日三餐广厦万间只睡卧榻三尺良田千顷不过一日三餐广厦万间只睡卧榻三尺卧尺卧尺厦万间只睡卧榻三尺卧尺厦万榻三尺卧尺卧尺榻三间只睡三</div>

<script>
// 默认字体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; // 在函数内部访问 eleTips
        
        console.log('当前字号:'+fontSize+'px,当前宽度:'+currWidth+',偏差宽度:'+(currWidth-maxWidth));
        
		//console.log(currWidth)
        if (fontSize <= minSize || maxWidth >= currWidth) {
            break;
        }

        fontSize--;
    }

    return fontSize;
}

</script>
<style>
    div#content {
        width: 290px;
        height: 170px;
        border: 1px solid red;
        font: 16px arial, sans-serif;
        word-wrap: break-word;
    }
</style>
</body>
</html>

演示效果:

相关推荐
geovindu2 小时前
css: Timeline scribble
前端·css·iphone
沙漠之主10 小时前
C++编程教学设计资料:从入门到实战的完整课程方案
java·前端·c++
hasty10 小时前
不上传新包,也能改变用户拿到的版本:npm dist-tag 的 OIDC 权限治理
前端·npm·node.js
Csvn11 小时前
diff 算法(虚拟 DOM Reconciliation)
前端
前端snow12 小时前
ai agent --- 文件存储
前端
Frag0ut12 小时前
Chrome四大版本获取及共存指南:Stable/Beta/Dev/Canary
前端·chrome·浏览器·dev·beta·canary·共存版
IT_陈寒13 小时前
SpringBoot自动配置坑了我一把,原来是这样绕过去的
前端·人工智能·后端
广州华水科技13 小时前
单北斗GNSS变形监测在大坝安全监测中的应用与优势
前端
zeng不错14 小时前
B站 173 个投稿活动看到眼瞎?我写了个扩展,主打一个精准打击
前端
Latchh14 小时前
前端导出的JPEG红字发糊,质量要拉到100才清楚
前端·图像处理·人工智能·计算机视觉