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


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

p5.j​​s中的createWriter()函數用於創建p5.PrintWriter對象,該對象可用於寫入或打印到各種可用流。

用法:

createWriter( name, [extension] )

參數:該函數接受上麵提到和下麵描述的兩個參數。

  • name:它是一個字符串,表示要創建的文件的名稱。
  • extension:它是一個字符串,指定文件的擴展名。它是一個可選參數。

返回值:它返回一個指示書寫器的p5.PrintWriter對象。

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



範例1:

let fwriter; 
  
function setup() { 
  createCanvas(600, 300); 
  textSize(18); 
  
  // Create a textarea for the input of text 
  inputArea = createElement("textarea"); 
  inputArea.position(30, 50); 
  inputArea.size(300, 100); 
  
  // Create a button for saving text 
  saveBtn = createButton("Save text"); 
  saveBtn.position(30, 160); 
  saveBtn.mousePressed(saveFile); 
  
  // Setup the writer 
  fwriter = createWriter("note.txt"); 
  
  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 
  for (line of stringList) { 
    fwriter.print(line); 
  } 
  
  // Close the writer 
  fwriter.close(); 
  
  // Clear the writer 
  fwriter.clear(); 
}

輸出:

writer-strings

範例2:

function setup() { 
  createCanvas(600, 300); 
  textSize(18); 
  
  // Create two inputs for the 
  // multiplication table 
  multiOf = createInput(); 
  multiOf.position(250, 50); 
  multiOf.size(50); 
  
  multiTo = createInput(); 
  multiTo.position(250, 80); 
  multiTo.size(50); 
  
  // Create a button for saving text 
  saveBtn = createButton("Generate and save to file"); 
  saveBtn.position(30, 120); 
  saveBtn.mousePressed(saveFile); 
  
  // Setup the writer 
  fwriter = createWriter("tables.txt"); 
} 
  
function draw() { 
  clear(); 
  text("Fill in the values to generate a multiplication table:", 20, 20); 
  text("Multiplication table of", 20, 60); 
  text("Multiplication table upto", 20, 90); 
} 
  
function saveFile() { 
  // Get the value of the two inputs 
  // and generate table 
  let multipicand = multiOf.value(); 
  let multiMax = multiTo.value(); 
  
  for (let multiplier = 1; multiplier <= multiMax; multiplier++) { 
    let textToWrite = 
      multipicand + " * " + multiplier + " = " + multipicand * multiplier; 
  
    // Print to the writer 
    fwriter.print(textToWrite); 
  } 
  
  // Close the writer 
  fwriter.close(); 
  
  // Clear the writer 
  fwriter.clear(); 
}

輸出:

writer-tables

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

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

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




相關用法


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