从数组值p5.js中绘制图像



我对p5.js相当陌生,但是我正在尝试阅读包含以下文本的。txt文件,并根据。txt文件中的值绘制图片。

00000年

20022年

00222年

22020年

11111年

我目前为如何根据数组中的数字绘制图像而感到困惑,例如"1"将是草。我使用以下代码将文件作为字符串加载:track = loadStrings("track1.txt");

如果你愿意,我正试图将其加载为5x5 'tile'。任何帮助都将是感激的:)

我用了p5。基于文件中的像素创建图片。

这是一种编写代码的方式:

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);
}

你可以把它分成数组,如果你有一些颜色的分隔符,像:track1.txt:10, 30, 255n ...r, g, bn ...。现在你必须使用rgbrrrgggbbb

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)

很可能有更好的方法,但至少这工作…

最新更新