How To Get The Bounding Box Of A Text Using Html5 Canvas?
I would like to get some text's bounding box.
Solution 1:
Works in Chrome:
const can = document.querySelector('canvas');
const ctx = can.getContext('2d');
let x = 10, y = 50;
let msg = "Hello, World!";
ctx.font = "30px monospace";
let textMetrics = ctx.measureText(msg);
ctx.fillText(msg, x, y);
console.log(textMetrics);
ctx.beginPath();
ctx.moveTo(
x - textMetrics.actualBoundingBoxLeft,
y - textMetrics.actualBoundingBoxAscent
);
ctx.lineTo(
x + textMetrics.actualBoundingBoxRight,
y - textMetrics.actualBoundingBoxAscent
);
ctx.lineTo(
x + textMetrics.actualBoundingBoxRight,
y + textMetrics.actualBoundingBoxDescent
);
ctx.lineTo(
x - textMetrics.actualBoundingBoxLeft,
y + textMetrics.actualBoundingBoxDescent
);
ctx.closePath();
ctx.stroke();
canvas {
border: 1px solid black;
}
<canvas></canvas>
Post a Comment for "How To Get The Bounding Box Of A Text Using Html5 Canvas?"