Skip to content

Instantly share code, notes, and snippets.

@Oaphi
Last active December 7, 2020 04:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Oaphi/5836d89933a5c8e84691b809d9530c5a to your computer and use it in GitHub Desktop.
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)
/**
* @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