Closed Bug 1363684 Opened 4 years ago Closed 5 months ago

tip faster js offsetwith

Categories

(Developer Documentation Graveyard :: JavaScript, enhancement, P5)

All
Other
enhancement

Tracking

(Not tracked)

RESOLVED WONTFIX

People

(Reporter: peter.mlich, Unassigned)

References

()

Details

:: Developer Documentation Request

      Request Type: Correction
     Gecko Version: 55 Branch
 Technical Contact: 

:: Details

I trying find fast method to detect position and widht columns of table with 800 rows. OffsetWidth is slow. I find something in google.

Somebody 1 - use create div, append body, innerHTML text, get offsetWidth
Somebody 2 - use canvas, put text, get metric width
2 is faster (tnative = 410, t1 = 460, t2 = 80).

function getTextWidth(text, font) {
    // re-use canvas object for better performance
    var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
    var context = canvas.getContext("2d");
    context.font = font;
    var metrics = context.measureText(text);
    return metrics.width;
}
getTextWidth.canvas = document.createElement("canvas")
MDN Web Docs' bug reporting has now moved to GitHub. From now on, please file content bugs at https://github.com/mdn/sprints/issues/ and platform bugs at https://github.com/mdn/kuma/issues/.
Status: UNCONFIRMED → RESOLVED
Closed: 5 months ago
Resolution: --- → WONTFIX
You need to log in before you can comment on or make changes to this bug.