loadStrings()函數用於讀取文件的內容,並使用文件的每一行創建一個字符串數組。如果使用文件名,則要讀取的文件必須位於草圖目錄中,否則,可以指定文件的URL。
建議在preload()函數中調用此函數,以確保該函數先於其他函數執行。
用法:
loadStrings( filename, callback, errorCallback )
參數:該函數接受上麵提到並在下麵描述的三個參數:
- filename:這是一個字符串,表示文件名或從中加載文件的URL。
- callback:這是在函數成功執行後調用的函數。該函數的第一個參數是字符串數組。
- errorCallback:如果執行該函數時有任何錯誤,則調用該函數。此函數的第一個參數是錯誤響應。
以下示例說明了p5.js中的loadStrings()函數:
範例1:
let result;
function preload() {
result = loadStrings("test_file.txt");
}
function setup() {
createCanvas(600, 300);
textSize(22);
}
function draw() {
clear();
text("The contents of the file "
+ "are shown below:", 20, 20);
// Check if the strings array
// is non-empty before displaying
// the contents
if (result.length > 0) {
for (let i = 0; i < result.length; i++) {
text(result[i], 20, 60 + i * 20);
}
}
else {
text("File is empty", 20, 60);
}
}
輸出:
範例2:
let result;
function setup() {
createCanvas(600, 300);
textSize(22);
text("The file would be loaded"
+ " below...", 20, 20);
result = loadStrings(
"test_file.txt", fileLoaded);
}
function fileLoaded() {
text("The contents of the file "
+ "are shown below:", 20, 60);
// Check if the strings array
// is non-empty before
// displaying the contents
if (result.length > 0) {
for (let i = 0; i < result.length; i++) {
text(result[i], 20, 100 + i * 20);
}
}
else {
text("File is empty", 20, 60);
}
}
輸出:
在線編輯: https://editor.p5js.org/
環境設置: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
參考: https://p5js.org/reference/#/p5/loadStrings
相關用法
- d3.js d3.rgb()用法及代碼示例
- PHP cos( )用法及代碼示例
- d3.js d3.lab()用法及代碼示例
- p5.js log()用法及代碼示例
- d3.js d3.hcl()用法及代碼示例
- p5.js tan()用法及代碼示例
- d3.js d3.map.set()用法及代碼示例
- p5.js sin()用法及代碼示例
- d3.js d3.max()用法及代碼示例
- PHP Ds\Map put()用法及代碼示例
- p5.js int()用法及代碼示例
- PHP max( )用法及代碼示例
注:本文由純淨天空篩選整理自sayantanm19大神的英文原創作品 p5.js | loadStrings() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。