📜  p5.js | createWriter()函数

📅  最后修改于: 2022-05-13 01:56:28.973000             🧑  作者: Mango

p5.js | createWriter()函数

p5.js 中的createWriter()函数用于创建 p5.PrintWriter 对象,该对象可用于写入或打印到各种可用流。

句法:

createWriter( name, [extension] )

参数:此函数接受两个参数,如上所述和如下所述。

  • name:它是一个字符串,表示要创建的文件的名称。
  • 扩展名:它是一个字符串,指定文件的扩展名。它是一个可选参数。

返回值:它返回一个 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();
}

输出:

作家字符串

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

输出:

写表

在线编辑器: https://editor.p5js.org/

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

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