I have file in javascript i am opening using
fs.readFileSync(fileName)
after I return it to the client it is stored like so:
[G]Hey, where did [C]we go, da[G]ys when the ra[D]ins came
[G]Down in the holl[C]ow, [G]playin' a ne[D]w game
However, I need the x and y coordinates so that I can update my canvas.
Is there any way to do this?
If we assume the first character has the position {x: 0, y: 0}
and that the next line increments the y position by one, then we can use something like this to calculate the positions of the characters:
/** * Find the XY positions of this string * * @type {string} */ const given = `[G]Hey, where did [C]we go, da[G]ys when the ra[D]ins came [G]Down in the holl[C]ow, [G]playing a ne[D]w game`; /** * Return the coordinates of the characters in a string * * @param {string} string * @returns {Array} */ const calculateXY = (string) => { const positions = []; let yIndex = 0; let xIndex = 0; string.split('').forEach(character => { if(/\\n/g.test(character)) { yIndex++; xIndex = 0; } else { positions.push({ [character]: { x: xIndex, y: yIndex}}); } xIndex++; }); return positions; }; const result = calculateXY(given); console.log(result);
You can modify the above block an pass a multiplier so that x and y are incremented by the distance in pixels to the next character.
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.