There is no direct way to achieve what you want, it will be a bounding rectangle of vector text paths.
If you are fine with the rough solution, render the text on a blank canvas, use getImageData to check the transparency of all pixels, and calculate max and min x and y where you will find the filled dots. This is far from ideal, but you cannot get the best solution easily.
I suppose there might be server side solutions, but I don't know anything.
And in theory, you could create your own font rendering engine in JS, and so you would have perfect bounding boxes, but, with the exception of simple / toy cases, a serious text layout mechanism takes years and years, so I guess that it is completely beyond the scope.
If you need help with the approximation method, tell me and I will give an example.
Edited to provide an example:
function getVisiblePixelsBoundingBox(canvas) { const context = canvas.getContext("2d"); const imageData = context.getImageData(0, 0, canvas.width, canvas.height).data; let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity; for (let y = 0; y < canvas.height; y++) { for (let x = 0; x < canvas.width; x++) { const alpha = imageData[(y * canvas.width + x) * 4 + 3]; if (alpha > 0) { minX = Math.min(minX, x); minY = Math.min(minY, y); maxX = Math.max(maxX, x); maxY = Math.max(maxY, y); } } } return { left: minX, top: minY, width: maxX - minX, height: maxY - minY }; }
Ok, so this seems good, but beware of the problems:
Accuracy is limited by pixels, therefore, although it is completely suitable for drawing a bounding box, it is not very convenient for operations that require much higher accuracy, for example, perfectly aligned shapes. In addition, due to the measurement method, if part of the form is so thin that it is not visible at all, then it will not be measured (this is probably not a big problem for you, because extremely thin figures do not occur in fonts).
Doing this can be slow, as we iterate through all the pixels to get the result (and JS doesn't work specifically for this). Knowing this, you may be tempted to try to reduce the size of the canvas and not use the same canvas of your target canvas, but I advise you not to, because it will introduce new problems with the next point.
If you measure when your text goes beyond the canvas, the bounding box will be limited to the visible area (it will adhere to the borders). You might consider increasing the size of the canvas, if that happens, to get the actual width and height, but if you don't limit the font size and the amount of text, you can put it on the canvas so large that it slows down the browser or maybe even breaks it ... Therefore, I would simply agree that the bounding box sticks to the borders. You might consider using the width provided by measureText , but unfortunately, to get the height and height, you need to scan the entire image.
user8811940
source share