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

时间:2018-08-31 07:34:50

标签: javascript canvas

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

是行为还是问题?如何达到我的要求。

1 个答案:

答案 0 :(得分:-1)

是的,您将使用不同的字体获得不同的大小。

只需将其可视化即可查看其功能,这是一个基于您的代码的示例:

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>

有了它,您可以检测文本是否适合父项或具有某些特殊效果