可以服务端跑一个接口,接受汉字,返回从字体包中拆出的字体.
参考我这个DEMO
浏览器端:
@font-face {
font-family: "my-font";
src: url('/font?str=天地玄黄宇宙洪荒') format('truetype');
}
<p style="font-family: 'my-font'">天地玄黄 宇宙洪荒</p>
服务端(nodejs)
// route.js
var express = require("express");
var router = express.Router();
const font = require("../src/font");
/* GET home page. */
router.get("/", function (req, res, next) {
res.render("index", {title: "Express"});
});
router.get("/font", async function (req, res, next) {
if (!req.query.str) {
res.send("str is required!");
return;
}
const result = await font.format(req.query.str);
if (!result.success) {
res.send("format failed!");
return;
}
res.send(result.data);
});
module.exports = router;
// font.js
const Fontmin = require("fontmin");
const format = (text) => {
return new Promise(resolve => {
const fontmin = new Fontmin()
.src("assets/font.ttf")
.use(Fontmin.glyph({
text,
hinting: false,
}));
fontmin.run((err, data) => {
if (err) {
console.log("error", err);
resolve({success: false, data: err});
return;
}
resolve({success: true, data: data[0]._contents});
});
});
};
module.exports = {
format
};
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…