【问题标题】:Read Coordinates from file in javascript在javascript中从文件中读取坐标
【发布时间】:2018-01-28 03:26:17
【问题描述】:
我在 javascript 中有文件,我正在使用
打开
fs.readFileSync(fileName)
在我将它返回给客户端后,它的存储方式如下:
[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
但是,我需要 x 和 y 坐标才能更新画布。
有什么办法吗?
【问题讨论】:
标签:
javascript
string
file
coordinates
【解决方案1】:
如果我们假设第一个字符的位置为{x: 0, y: 0},并且下一行将 y 位置加一,那么我们可以使用类似的方法来计算字符的位置:
/**
* 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);
您可以修改上面的块并传递一个乘数,以便 x 和 y 增加到下一个字符的距离(以像素为单位)。