javascript - cavsTxt.measureText 根据字体系列和字体大小为文本提供不同的宽度
问题描述
我想使用 cavsTxt.measureText 查找文本元素的宽度。根据宽度,我会检查它是否从父元素溢出。在更改字体系列及其大小时,我得到了不同的宽度。
cavsElem = document.createElement("canvas");
cavsTxt = cavsElem.getContext("2d");
//when font family as Calibri and size as 11pt
cavsTxt.font = "11pt Calibri normal";
width = cavsTxt.measureText("Clear green fluorite with tiny crystals of
pyrite on top").width // 313.88671875
//when font family as arial and size as 10pt
cavsTxt.font = "13px arial normal";
width = cavsTxt.measureText("Clear green fluorite with tiny crystals of
pyrite on top").width // 285.4099426269531
是行为还是问题?如何达到我的要求。
解决方案
是的,您将使用不同的字体获得不同的大小。
只需可视化它以查看它在做什么,这是基于您的代码的示例:
var text = "Clear green fluorite with tiny crystals of pyrite on top ."
var canvas = document.getElementById("canvas");
cavsTxt = canvas.getContext("2d");
function drawText(font, x, y) {
cavsTxt.beginPath();
cavsTxt.font = font;
width = cavsTxt.measureText(text).width
cavsTxt.lineWidth = 20;
cavsTxt.strokeStyle = "red";
cavsTxt.moveTo(x+5, y+15);
cavsTxt.lineTo(width + x+5, y+15);
cavsTxt.stroke();
cavsTxt.fillText(cavsTxt.font, x, y);
cavsTxt.fillText(text, x+5, y+20);
cavsTxt.fillText(width, width+15, y+20);
}
//when font family as Calibri and size as 11pt
drawText("11pt Calibri normal", 5, 15);
//when font family as arial and size as 10pt
drawText("13px arial normal", 5, 55);
drawText("13px arial", 5, 95);
drawText("bold 13px arial", 5, 140);
<canvas id="canvas" height=175 width=500 style="border:1px solid #000000;">
</canvas>
有了它,您可以检测文本是否适合父母或做一些特殊效果
推荐阅读
- python - Image to URL 函数返回同一张图片的不同结果
- pine-script - 如何在图表上标记目标命中
- html - 如何使用 Windows 在 R 版本 3.6.1 上安装 ReportingTools 包
- arrays - 如何使这个数组分配在 php5.6 中工作?
- solr - solr,索引前的数据验证
- chart.js - 多轴折线图
- neo4j - 如何根据 Cypher 中的属性创建节点链
- reporting-services - Power BI 报表服务器连接字符串问题
- flutter - 如何将用户挑选的视频上传到firebase?
- html - 居中按钮使用整行