當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


p5.js loadStrings()用法及代碼示例

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

輸出:
loadString-preload

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

輸出:
loadStrings-callback

在線編輯: https://editor.p5js.org/

環境設置: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/

參考: https://p5js.org/reference/#/p5/loadStrings




相關用法


注:本文由純淨天空篩選整理自sayantanm19大神的英文原創作品 p5.js | loadStrings() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。