Reputation: 97
I tried this code below..
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);
I want the blue background to fit based on the text. It seems okay in some scenario, but the problem is, the text is dynamically changing, and the blue background sometimes is short when I made my text just 1-4 small characters, and when I made it long and in all-caps, the blue background is getting too long. I want it to be fit and have at least small padding in the beginning and end of the text. P.S: The text font size and font family is fixed at 90px Arial, but the "bold" will.
Upvotes: 2
Views: 118
Reputation: 33044
The main idea is to measure the text before filling the rect. Next you fill the rect using the width of the text, and finally you fill the text. I hope it helps.
Observation: you may need to reset the width of the canvas if it's smaller than needed. You can do it after filling the rect and the 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>
Upvotes: 2