0

I'm making a lyrics + chords display, and I want to take this raw format:

[Dm]Hello darkness my old [C]friend

And put the chords above the lyrics. I can do it by making each word a div, and making the chord absolute/relative to the word, however that means people can't copy and paste everything into a WYSIWYG editor like Word.

So instead I want to have a line above the lyrics that is padded out with spaces, like this:

Dm                    C
Hello darkness my old friend

It's easy with monospace text, but I want to use fonts like Arial/Times. Is there a way to calculate how many spaces would approximate the length of some text?

Note—before everyone says "oh you should use a different method to display the chords", I've tried a few methods, but I'm specifically looking for something I can copy and paste without losing chord placement.

Mirror318
  • 11,875
  • 14
  • 64
  • 106
  • there's a method in js for this (measureText) https://stackoverflow.com/a/21015393/1675954 p.s. this question has already been asked a few times.. search! – Rachel Gallen Jun 27 '18 at 23:55
  • Thanks for the link @RachelGallen, I was specifically wanting the width in spaces, not just px, but that helps – Mirror318 Jun 28 '18 at 00:27
  • Glad to be of some help. I think I have a fiddle somewhere, but not on my computer now. You could Google px to size of space? – Rachel Gallen Jun 28 '18 at 00:29

1 Answers1

1

The CanvasRenderingContext2D interface has a text metric method measureText that can be used to obtain the width of text.

It takes two parameters, the text to measure and a CSS font value.

A canvas element used in the process does not have to be part of the document, nor have width or height properties just to use measureText.

Example of the concept:

"use strict";

const ctx = document.createElement("CANVAS").getContext("2d");

function getTextWidth(text, cssFont) {
    ctx.font = cssFont;
    var o = ctx.measureText(text);
    return o.width;
}

var cssFont = "14px Arial";
var spaceWidth = getTextWidth( "          ", cssFont) / 10;
var lyric = "Hello darkness my old "
var lyricWidth = getTextWidth("Hello darkness my old ", cssFont);

console.log('"' + lyric + '"' + " width is " + lyricWidth);
console.log("space width is " + spaceWidth);
console.log("So the lyric width is " + lyricWidth/spaceWidth + " spaces");
traktor
  • 17,588
  • 4
  • 32
  • 53