简体   繁体   中英

JavaScript convert text to pixel coordinates

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?

Eg 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM