p5.Table addRow() Method
The addRow() method of p5.Table in p5.js is used to add a new row of data to the table object. This method creates an empty row by default. This can be used by storing a reference to the new row object and then setting the values in the row using the set() method. Alternatively, a p5.TableRow object can be included as a parameter to the method. This will directly duplicate the given row and add it to the table.
Syntax:
addRow( [row] )
Parameters: This function accept a single parameter as mentioned above and described below:
- row: It is a p5.TableRow object that specifies the row to be added to the table. It is an optional parameter.
Below example illustrates the addRow() function in p5.js:
Example 1:
javascript
function setup() { createCanvas(500, 300); textSize(16); addRowBtn = createButton( "Add Row" ); addRowBtn.position(30, 40); addRowBtn.mouseClicked(addNewRow); // Create the table table = new p5.Table(); table.addColumn( "author" ); table.addColumn( "language" ); } function addNewRow() { // Create new row object let newRow = table.addRow(); // Add data to it using setString() newRow.setString( "author" , "Author " + floor(random(1, 100))); newRow.setString( "langauge" , "Langauge " + floor(random(1, 100))); } function draw() { clear(); // Show the total number of rows text( "The table has " + table.getRowCount() + " rows" , 20, 20); // Show the columns text( "Author" , 20, 80); text( "Language" , 120, 80); // Show the table with the rows for (let r = 0; r < table.getRowCount(); r++) for (let c = 0; c < table.getColumnCount(); c++) text(table.getString(r, c), 20 + c * 100, 120 + r * 20); } |
Output:
Example 2:
javascript
function setup() { createCanvas(500, 300); textSize(16); addRowBtn = createButton( "Add Row" ); addRowBtn.position(30, 40); addRowBtn.mouseClicked(addNewRow); // Create the table table = new p5.Table(); table.addColumn( "author" ); table.addColumn( "book" ); } function addNewRow() { // Create a new TableRow object let tableRow = new p5.TableRow( "Author X, Book Y" , "," ); // Add the TableRow to table table.addRow(tableRow); } function draw() { clear(); // Show the total number of rows text( "The table has " + table.getRowCount() + " rows" , 20, 20); // Show the columns text( "Author" , 20, 80); text( "Book" , 120, 80); // Show the table with the rows for (let r = 0; r < table.getRowCount(); r++) for (let c = 0; c < table.getColumnCount(); c++) text(table.getString(r, c), 20 + c * 100, 120 + r * 20); } |
Output:
Online editor: https://editor.p5js.org/
Environment Setup: https://www.w3wiki.net/p5-js-soundfile-object-installation-and-methods/
Reference: https://p5js.org/reference/#/p5.Table/addRow
Contact Us