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>

演示效果:

最近更新

  1. TCP协议是安全的吗?

    2024-02-23 20:02:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-02-23 20:02:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-02-23 20:02:01       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-02-23 20:02:01       20 阅读

热门阅读

  1. ERC721解读

    2024-02-23 20:02:01       31 阅读
  2. 计算机网络中的与或非运算

    2024-02-23 20:02:01       36 阅读
  3. Redis之缓存雪崩问题解决方案

    2024-02-23 20:02:01       29 阅读
  4. 使用Python创建一个简单的Discord机器人

    2024-02-23 20:02:01       33 阅读
  5. 2.22号qt

    2024-02-23 20:02:01       28 阅读
  6. 【Git】 删除远程分支

    2024-02-23 20:02:01       34 阅读
  7. 在C++程序中给视频添加文字水印

    2024-02-23 20:02:01       28 阅读
  8. win7 使用openssh

    2024-02-23 20:02:01       32 阅读
  9. http管道化

    2024-02-23 20:02:01       24 阅读
  10. 100条经典C语言题第二天(10-20)

    2024-02-23 20:02:01       28 阅读
  11. Go 线程池实现案例

    2024-02-23 20:02:01       27 阅读