【问题标题】:How to determine the accurate fillRect() width based on the fillText() width?如何根据fillText()宽度确定准确的fillRect()宽度?
【发布时间】:2019-07-11 03:44:09
【问题描述】:

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

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 个小字符时,蓝色背景有时会很短,而当我将其设为长且全大写时,蓝色背景变得太长。我希望它适合并且在文本的开头和结尾至少有小填充。 P.S:文字字体大小和字体系列固定为90px Arial,但“粗体”会。

【问题讨论】:

    标签: javascript html5-canvas


    【解决方案1】:

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

    观察:如果画布的宽度比需要的小,您可能需要重置画布的宽度。填完rect和text就可以了。

    // 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>

    【讨论】:

    • 谢谢,这个答案正是我想要的。
    猜你喜欢
    • 2013-02-12
    • 2011-07-23
    • 2011-08-30
    • 2010-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-20
    • 2021-04-06
    相关资源
    最近更新 更多