我希望有人能帮助我解决以下问题:我需要获得文本的精确大小。仅测量一个span之类的大小不足以满足我的需求。
Right now, I am using a canvas to find the non-transparent pixels in the canvas. This is my code:
// a function to draw the text on the canvas
let text = "Hello World";
let canvas = document.getElementById('happy-canvas');
let width = 1000
let height = 100
canvas.width = width
canvas.height = height
let ctx = canvas.getContext('2d');
ctx.save();
ctx.font = "30px cursive";
ctx.clearRect(0, 0, width, height);
ctx.fillText(text, 0, 60);
// get the image data
let data = ctx.getImageData(0, 0, width, height).data,
first = false,
last = false,
r = height,
c = 0
// get the width of the text and convert it to an integer
const canvWidth = parseInt(ctx.measureText(text).width)
//Find the last line with a non-transparent pixel
while (!last && r) {
r--
for (c = 0; c < width; c++) {
if (data[r * width * 4 + c * 4 + 3]) {
last = r
break
}
}
}
let canvasHeight = 0
// Find the first line with a non-transparent pixel
while (r) {
r--
for (c = 0; c < width; c++) {
if (data[r * width * 4 + c * 4 + 3]) {
first = r
break
}
}
canvasHeight = last - first
}
//draw a rectangle around the text
ctx.strokeRect(0, first, canvWidth, canvasHeight)
<div> The last "d" is not completely inside of the the box
<canvas id="happy-canvas" width="150" height="150"> I wonder what is here</canvas>
</div>
下面是一个示例: 黑盒子是测量的尺寸。正如你所看到的,“measureText”并没有得到正确的宽度。现在我已经没有任何想法,我还能做什么。
if (font.capitalize)
中的 font 是什么? - Mark Schultheissif (font.capitalize)
。它对于这个例子来说是无关紧要的。上面的代码片段现在是一个可工作的示例。画布的字体是“草书”,“Hello World”的最后一个“d”没有完全在框内。 - pixelbashgetImageData()
的工作原理。我将在一分钟内发布我的解决方案。 - pixelbash