P Kero
P Kero

Reputation: 77

How to calculate width of a string variable in pixels using Javascript/JQuery

Continuing with my SVG charts project, I have created the labels for the chart (e.g. Bar chart here) as string variables such as

//Bar Chart series
var barData = [{
                label: "Eating",
               }, {
                label: "Working",
               }, {
                label: "Sleeping",
               }];

I need to calculate the width of each label in pixels to create a legend. I want to take the width of the longest label so that the legend width can be calculated accordingly. The code is as follows:

function legendWidth(paper, config, series){

    var labelWidth = 0;
    for (var n = 0; n < series.length; n++) {
        var label = series[n].label;
        labelWidth = Math.max(labelWidth, label.width);
    }
}

The label.width returns a NaN value. Is there a way to calculate the width in pixels of the text in label?

Edit: Also, I don't know if this is of any help, but this project has already been completed in canvas. In canvas the method used was

labelWidth = Math.max(labelWidth, context.measureText(label).width);

Upvotes: 2

Views: 1535

Answers (2)

yarmyarch
yarmyarch

Reputation: 1

The width depends on the font you're using, so it's not a easy job doing that and there may always exist the performance issue.

However you can still do it like this:

var dom = document.createElement("div"),
    maxWidth = 0;
dom.style.cssText = "display:block;width:0;border:0;margin:0;padding:0;overflow:hidden;";
document.body.appendChild("dom");

for (var i in barData) {
    dom.innerHTML = barData[i].label;
    maxWidth = Math.max(maxWidth, dom.scrollWidth);
}

Now you get your max width in pixels.

Upvotes: 0

pax162
pax162

Reputation: 4735

If you want to get the width of the SVG element containing the text, instead of the length of the text itself, you can do this:

var width = $(element)[0].getBoundingClientRect().width;

Where element is the SVG element.

Upvotes: 1

Related Questions