gpt4 book ai didi

javascript - cavsTxt.measureText 根据字体系列和字体大小为文本提供不同的宽度

转载 作者:行者123 更新时间:2023-11-30 06:50:38 25 4
gpt4 key购买 nike

我想使用 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>

有了它你可以检测文本是否适合父级或做一些特殊效果

关于javascript - cavsTxt.measureText 根据字体系列和字体大小为文本提供不同的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52110633/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com