Home > Back-end >  Draw an image from an array value p5.js
Draw an image from an array value p5.js

Time:09-28

I am fairly new to p5.js, however I am trying to read a .txt file which contains the below text, and draw a picture depending on the value within the .txt file.

00000

20022

00222

22020

11111

I am currently stumped as to how to draw an image depending on the number in the array, as an example '1' would be grass. I have loaded the file in as a string using the following code: track = loadStrings("track1.txt");

I am trying to load it as a 5x5 'tile' if you will. Any help would be appreciated :)

CodePudding user response:

I've used p5.Image to create a picture based on the pixels in the file.

This is a way of writing the code:

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

CodePudding user response:

Well you could probs split it up into arrays and also if you'd have some sort of seperator for colors, like: track1.txt: 10, 30, 255\n ... r, g, b\n .... Right now you would have to use the 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]))

   }

I also made a function with a slightly different formula, which might work better, i am not sure though, but this is the actual formula to get from pixel array

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)

THERE IS MOST LIKELY IS A BETTER WAY TO DO THIS, but at least this works...

  • Related