Skip to content

Instantly share code, notes, and snippets.

@uguisu-an
Created August 25, 2019 05:03
Show Gist options
  • Save uguisu-an/2c6cb388856ef269f3e54ac2a6a9617f to your computer and use it in GitHub Desktop.
Save uguisu-an/2c6cb388856ef269f3e54ac2a6a9617f to your computer and use it in GitHub Desktop.
フォントサイズの自動計算
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<link
href="https://fonts.googleapis.com/css?family=Anton|Lobster|M+PLUS+1p|Noto+Sans+JP|Noto+Serif+JP&display=swap"
rel="stylesheet"
/>
</head>
<body>
<div
id="canvas-hidden"
style="visibility: hidden; overflow: hidden; width: 0; height: 0;"
></div>
<div
id="target1"
style="width: 100px; overflow: visible; box-sizing: border-box; border: 1px solid gray;"
></div>
<div
id="target2"
style="width: 768px; overflow: visible; box-sizing: border-box; border: 1px solid gray;"
></div>
<div
id="target3"
style="width: 1500px; overflow: visible; box-sizing: border-box; border: 1px solid gray;"
></div>
<script>
const createTextElement = (text, fontFamily, fontSize) => {
const span = document.createElement("span");
span.style.fontSize = `${fontSize}px`;
span.style.fontFamily = fontFamily;
span.style.whiteSpace = "nowrap";
span.innerText = text;
return span;
};
const getTextWidth = (text, fontFamily, fontSize) => {
const span = createTextElement(text, fontFamily, fontSize);
const canvas = document.getElementById("canvas-hidden");
canvas.appendChild(span);
return span.getBoundingClientRect().width;
};
const computeFontSize = (text, fontFamily, targetWidth) => {
const baseFontSize = 120;
const baseWidth = getTextWidth(text, fontFamily, baseFontSize);
if (baseWidth > 0) {
const widthScale = targetWidth / baseWidth;
return Math.floor(baseFontSize * widthScale);
} else {
return 0;
}
};
const test = (text, fontFamily, target) => {
const t = document.getElementById(target);
const targetWidth = t.getBoundingClientRect().width;
const fontSize = computeFontSize(text, fontFamily, targetWidth);
console.info("fontSize", fontSize);
const span = createTextElement(text, fontFamily, fontSize);
t.appendChild(span);
console.info("width", span.getBoundingClientRect().width);
};
document.addEventListener("DOMContentLoaded", () => {
test("Hello にち World!!", "Noto Sans JP", "target1");
test("こんにちわんこ Dogs", "Anton", "target2");
test("色即是空 Cool So Cool", "Noto Serif JP", "target3");
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment