Last active
December 7, 2020 04:25
-
-
Save Oaphi/5836d89933a5c8e84691b809d9530c5a to your computer and use it in GitHub Desktop.
Preciser text width measure (single line, obviously needs transpiling for the browser detection to work)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/TextMetrics} | |
* @summary measure text width | |
* @param {CanvasRenderingContext2D} ctx drawing context | |
* @returns {number} | |
*/ | |
const measureWidth = (ctx, text) => { | |
const measurement = ctx.measureText(text); | |
if (!("actualBoundingBoxLeft" in measurement)) /* IE, use width */ { | |
return measurement.width; | |
} | |
const { actualBoundingBoxLeft, actualBoundingBoxRight } = measurement; | |
return Math.abs(actualBoundingBoxLeft) + Math.abs(actualBoundingBoxRight); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment