首页 > 解决方案 > 如何根据fillText()宽度确定准确的fillRect()宽度?

问题描述

我在下面尝试了这段代码..

var text = "Sample Text";
var b1 = "Bold";
var txtContext = txtCanvas.getContext("2d");
var width = txtContext.measureText(text).width;

txtContext.fillStyle = "blue";
txtContext.fillRect(0, 0, width * 9.7, height);

txtContext.textBaseline = "middle";
txtContext.fillStyle = 'gray';
txtContext.font = b1 + "90px Arial";
txtContext.fillText(text, 10, 50);

我希望蓝色背景适合文本。在某些情况下似乎还可以,但问题是,文本是动态变化的,当我将文本设为 1-4 个小字符时,蓝色背景有时会很短,而当我将其设为长且全大写时,蓝色背景变得太长。我希望它适合并且在文本的开头和结尾至少有小填充。PS:文本字体大小和字体系列固定为 90px Arial,但“粗体”会。

标签: javascripthtml5-canvas

解决方案


主要思想是在填充矩形之前测量文本。接下来使用文本的宽度填充矩形,最后填充文本。我希望它有所帮助。

观察:如果画布比需要的小,您可能需要重置画布的宽度。您可以在填写矩形和文本后执行此操作。

// set the canvas width
txtCanvas.width = window.innerWidth;
//and the context
var txtContext = txtCanvas.getContext("2d");


var text = "Sample Text";
var b1 = "bold";
txtContext.textBaseline = "middle";
txtContext.font = b1 + " 90px arial";

//measure the text before filling it
var width = txtContext.measureText(text).width;
//fill the rect using the width of the text
txtContext.fillStyle = "blue";
txtContext.fillRect(0, 0, width + 20, 100);// + 20 since the text begins at 10
//fill the text
txtContext.fillStyle = 'gray';
txtContext.fillText(text, 10, 50);
<canvas id="txtCanvas"></canvas>


推荐阅读