我是p5.js的新手,但是我正在尝试读取一个包含以下文本的.txt文件,并根据.txt文件中的值绘制一幅图片。
00000
20022
00222
22020
11111
我现在不知道如何根据数组中的数字来绘制图像,例如'1‘就是草。我使用以下代码将文件作为字符串加载: track = loadStrings("track1.txt");
如果你愿意的话,我正试着把它加载成一个5x5的“磁贴”。如有任何帮助,我们将不胜感激:)
发布于 2021-09-28 14:40:23
我已经使用p5.Image根据文件中的像素创建了一个图片。
这是一种编写代码的方式:
let track;
let colors;
let img;
function setup() {
createCanvas(100, 100);
track=loadStrings("track1.txt")
colors = [color(255,0,0),color(0,255,0),color(0,0,255)]
}
function draw() {
background(220);
img = createImage(track.length, track[0].length)
img.loadPixels();
for (let i = 0 ; i < track.length ; i++){
for (let j = 0 ; j < track.length ; j++){
img.set(i, j, colors[int(track[i][j])]);
}
}
img.updatePixels();
image(img, 50, 50);
}发布于 2021-09-28 15:23:23
你可以把它分成数组,如果你有某种颜色分隔符的话,比如: track1.txt:10, 30, 255\n ... r, g, b\n ...。现在,您必须使用rgb rrrgggbbb。
let colors = track.split("\n") // makes every new line into an array
for(let x = 0; x <= width; x ++) // "\n" = new line
for(let y = 0; y <= height; y ++){
let currentCol = []
for(let i = 0; i < 9; i += 3)
currentCol.push(
colors[x + y][0 + i] + // I'm really not sure about the: colors[x + y]...
colors[x + y][1 + i] +
colors[x + y][2 + i]
)
set(x, y, color(currentCol[0], currentCol[1], currentCol[2]))
}我还用一个稍微不同的公式做了一个函数,这个公式可能会更好,但我不确定,但这是从像素数组得到的实际公式
function getColor(x, y, allColorsArr){
let _col = [] // current color, underscore not to accidentally clear your variable
for(let i = 0; i < 3; i ++)
_col.push(
allColorsArr[x + y * width][0 + i * 3] +
allColorsArr[x + y * width][1 + i * 3] +
allColorsArr[x + y * width][2 + i * 3]
)
return {
r: parseInt(_col[0], 10),
g: parseInt(_col[1], 10),
b: parseInt(_col[2], 10)
} // returning an object here just for the `.r`; `.g`; `.b`
} // you could do something like: let Colors = {red: 0, green: 1, blue: 2}
// col[Colors.red], col[Colors.green], col[Colors.blue] if you want
// example: let col = getColor(1, 0, track.split("\n"))
// example: stroke(col.r, col.g, col.b)很可能有一种更好的方法来做这个,但至少这是有效的.
https://stackoverflow.com/questions/69357330
复制相似问题