某個頁面有這樣一個需求:一個固定寬度的div,若文字過長,則縮小字型填充。
看到同事採用的是用php的GD庫的imagettfbbox函式來計算文字的寬度。
imagettfbbox(float $size
,float $angle
,string $font_filename
,string $string
,array $options
= []): array|false
取得使用 TrueType 字型的文字的邊界框,返回四個頂點的x和y座標值資料或者false
size
字型的尺寸,單位:點(磅)。
angle
測量字串的角度(以度為單位)。
fontfile
想要使用的 TrueType 字型的路徑。
string
要測量的字串。
<?php
function getFontSize($text)
{
$base_fs = 14;
$base_width = 150;
$fontfile = './fonts/Arial.ttf';
// 取得使用 TrueType 字型的文字的邊界框
//第一個引數單位pt,絕對尺寸單位,而px是相對尺寸單位和DPI有關,當DPI為72時,1pt等於1px,本例中假定DPI=72
$font_box = imagettfbbox($base_fs, 0, $fontfile, $text);
$width = $font_box[2] - $font_box[0];
if ($width > $base_width) {
$font_size = round($base_fs * ($base_width / ($font_box[2] - $font_box[0])), 2);
} else {
$font_size = $base_fs;
}
return compact('text', 'width', 'font_size');
}
$text_arr = [
'A1-I have a good time every day.',
'A2-I come from China.',
'M3-I enjoy going fishing.',
"我樂於和平地生活。",
"我來自中國。",
"我喜歡去釣魚。"
];
$res = [];
foreach ($text_arr as $text) {
$val = getFontSize($text);
$res[] = $val;
}
?>
<style>
* {
margin: 0;
padding: 0
}
div.text {
border: 1px solid red;
width: 150px;
height: 20px;
line-height: 20px;
font: normal 14px Arial;
}
</style>
<script>
console.log(<?= json_encode($res) ?>)
</script>
<div>
<?php foreach ($res as $row): ?>
<div class="text" style="font-size: <?= $row['font_size'] ?>px;"><?= $row['text'] ?></div>
<?php endforeach ?>
</div>
計算文字大小和客戶端的DPI有關,在server上計算感覺不是很適合,看看有沒有客戶端的解決方案。
<style>
* {
margin: 0;
padding: 0;
}
div.text {
border: 1px solid red;
width: 150px;
height: 20px;
line-height: 20px;
font: normal 14px Arial;
}
</style>
<div id="content"></div>
<div id="content_canvas"></div>
<script>
function getTextWidth(text) {
const font = "normal 14px Arial";
const element = document.createElement("span");
element.style.font = font;
element.style.visibility = "hidden";
element.textContent = text;
document.body.appendChild(element);
const width = element.offsetWidth;
document.body.removeChild(element);
return width;
}
function getTextWidthByCanvas(text) {
const font = "normal 14px Arial";
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");
context.font = font;
const metrics = context.measureText(text);
return metrics.width;
}
function getFontSize(width) {
const base_fs = 14;
const base_width = 150;
let font_size = 14;
if (width > base_width) {
font_size = (base_fs * (base_width / width)).toFixed(2);
}
return font_size;
}
const text_arr = ["I come from China.I have a good time every day.", "A2-I come from China.", "M3-I enjoy going fishing.", "我樂於和平地生活。", "我來自中國。", "我喜歡去釣魚。"];
function renderHtml(domId, type = "canvas") {
console.log(type, "--------------");
let html = "";
for (let text of text_arr) {
const width = type == "canvas" ? getTextWidthByCanvas(text) : getTextWidth(text);
const font_size = getFontSize(width);
console.log(text, width, font_size);
html += `<div class="text" style="font-size:${font_size}px;">${text}</div>`;
}
document.querySelector("#" + domId).innerHTML = html;
}
renderHtml("content", "elem");
renderHtml("content_canvas");
</script>
這種就好很多,文字較長時能夠縮小字型填充,且填充的寬度幾乎可以佔滿div