tip faster js offsetwith

UNCONFIRMED
Unassigned

Status

Developer Documentation
JavaScript
P5
normal
UNCONFIRMED
9 months ago
9 months ago

People

(Reporter: peter, Unassigned)

Tracking

Details

(URL)

(Reporter)

Description

9 months ago
:: 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")
You need to log in before you can comment on or make changes to this bug.