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


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

saveStrings()函數用於將字符串數組(每個字符串一行)寫入文件。文件的保存將因網絡瀏覽器而異。

用法:

saveStrings( list, filename, extension )

參數:該函數接受上麵提到並在下麵描述的三個參數:



  • list:它是必須寫入文件的字符串數組。
  • filename:它指定用作已保存文件的文件名的字符串。
  • extension:它指定用作已保存文件擴展名的字符串。它是一個可選參數。

以下示例說明了p5.js中的saveStrings()函數:

範例1:

function setup() { 
    createCanvas(600, 300); 
    textSize(22); 
   
    // Create a textarea for 
    // the input of text 
    inputArea = createElement('textarea'); 
    inputArea.position(30, 50) 
    inputArea.size(400, 120); 
   
    // Create a button for saving text 
    saveBtn = createButton("Save text"); 
    saveBtn.position(30, 200) 
    saveBtn.mousePressed(saveFile); 
} 
   
function draw() { 
    clear(); 
    text("Click on the button below to "
        + "save the written text", 20, 20); 
} 
   
function saveFile() { 
      
    // Get the value of the textarea 
    // and split the strings on the basis 
    // of the nextline character 
    stringList = inputArea.value().split("\n"); 
   
    // Save the strings to file 
    saveStrings(stringList, 'output.txt'); 
}

輸出:
save-text

範例2:

function setup() { 
    createCanvas(600, 300); 
    textSize(18); 
   
    // Create both inputs for the 
    // multiplication table 
    multiOf = createInput(); 
    multiOf.position(250, 50) 
    multiOf.size(50); 
   
    multiTo = createInput(); 
    multiTo.position(250, 90) 
    multiTo.size(50); 
   
    // Create a button for saving text 
    saveBtn = createButton( 
        "Generate and save table"); 
    saveBtn.position(30, 140) 
    saveBtn.mousePressed(saveFile); 
} 
   
function draw() { 
    clear(); 
    text("Fill in the input to generate "
        + "a multiplication table:", 20, 20); 
    text("Multiplication table of:", 20, 60); 
    text("Multiplication table upto:", 20, 100); 
} 
   
function saveFile() { 
      
    // Get the value of the two inputs 
    // and generate table 
    let mul = multiOf.value(); 
    let maxUpto = multiTo.value(); 
    let stringList = []; 
   
    for (let i = 0; i < maxUpto; i++) { 
        stringList[i] = mul + " * "
            + i + " = " + mul * i; 
    } 
   
    // Save the strings to file 
    saveStrings(stringList, 'output.txt'); 
}

輸出:
multiplication-table

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

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

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




相關用法


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