Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
114 views
in Technique[技术] by (71.8m points)

javascript - How to use CSV data and draw in p5.js

I'm so new to programming and JS. Please correct me at any point or if there is a better solution... I am trying to read the data from CSV which is like this: (193 rows including header)

Name, Model, IP, MAC
PC-1, unknown, 10.10.10.1, AA:22:BB:44:55:11
PC-2, unknown, 10.10.10.2, 11:22:33:44:55:22
PC-3, unknown, 10.10.10.3, 11:22:33:44:55:33
.
.
PC-192, unknown, 10.10.10.193 22.33.44.55.66.11

I want to create a map with all these entries and draw them as squares for each PC where Name, Model, IP, and MAC would show up for them when mouse clicked on that specific squares.

I have the following code which gets the data from CSV but I'm stuck on populating the data on the specific places that I have drawn squares. Ultimately, There would be 192 squares which I want to show network info for each.

function setup() {
  createCanvas(windowWidth, windowHeight);
  fill(0);
  getData();
}

async function getData() {
  const response = await fetch('test.csv');
  const data = await response.text();

  const rows = data.split('
').slice(1);
  rows.forEach(elt => {
  const row = elt.split(',')
  const name = row[0];
  const ip = row[2];
  const mac = row[3];
  for (i = 0; i < rows; i++){
    text(rows[i], 500,500);
  }

    // console.log(name, ip, mac);
    // return { name, ip, mac };
  });
}

function draw(){
    square(270, 280, 20); //PC-1
    square(430, 347, 20); //PC-2
    square(520, 180, 20); //PC-3
}

function mousePressed(){
  if (mouseX > 65 && mouseX < 135 && mouseY > 180 && mouseY < 205) {
    // not sure if here should ask CSV to retrive the data?
  }
}

I managed to remove the first row (header) with slice and I can see the data in Console. but I can't figure how to approach the problem..should I assign a variable to each entry in CSV? should everything be done in setup() or draw()? Please advice..

question from:https://stackoverflow.com/questions/65650077/how-to-use-csv-data-and-draw-in-p5-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is a better way to handle csv files in p5.js. You can use loadTable().

Link to loadTable docs: https://p5js.org/reference/#/p5/loadTable

All the data is loaded into an object. You can use it in mousePressed() function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...