4

In short, given a font (with size, weight, etc.) and a string, is there a way I extract an array of pixel coordinates relative to the top left of the first letter using JavaScript?

E.g. I might become

[
[0,0],
[0,1],
...
]

Edit: I am not looking for the bounding box, rather I am looking for the coordinates of each and every individual pixel that makes up the text. I need this information to essentially recreate the text later using squares.

Kevin Pei
  • 5,800
  • 7
  • 38
  • 55
  • If is a string you can use split function and it converts the string in an array or if you are using an object you can acces to the value using the index of the object – Jorge Mejia Apr 04 '16 at 21:45

1 Answers1

2

Yes, you can use the canvas element to obtain text metrics:

// setup canvas
var c = document.createElement("canvas"),
    ctx = c.getContext("2d");

// define (pre-loaded) font:
ctx.font = "bold 16px sans-serif";

// get metrics
var m = ctx.measureText("Hello");

The metrics object will give you the width and height etc. But - only width is currently supported in most browsers. There exists a poly-fill that will cover things like ascend and descend which you would need.

An alternative is to scan the bitmap to detect the rectangle the text coverts. I have given an answer here which covers this technique:

Javascript Method to detect area of a PNG that is not transparent

Also, if you only need the bounding box of the text (not pixel-accurate start point of the text itself) you can use a DOM element to get the width and height for that box. Here is one approach for that:

Use Javascript to get Maximum font size in canvas

Updated after clarification: For extracting pixels from the bitmap and convert those into points:

https://stackoverflow.com/a/30204783/1693593

Community
  • 1
  • 1
  • Perhaps I should clarify my question a little bit. I am not looking for the bounding box, rather I am looking for the coordinates of each and every individual pixel that makes up the text. I need this information to essentially recreate the text later using squares. – Kevin Pei Apr 04 '16 at 21:58
  • 1
    @KevinPei then you probably looking for something like this: http://stackoverflow.com/a/30204783/1693593 ? –  Apr 04 '16 at 22:02
  • 1
    exactly what I wanted! Thanks! :) – Kevin Pei Apr 04 '16 at 22:14
  • @KevinPei no problem! :) –  Apr 04 '16 at 22:16