簡體   English   中英

在 p5js 中調用 function 后,如何刪除顯示在 canvas 上的按鈕?

[英]How do I remove a button from being displayed on the canvas after a function is called in p5js?

我是 p5js 的初學者,我想弄清楚如何在調用 function drawInstructions 時刪除我添加到 function 設置的按鈕,使其不顯示在 canvas 上,但我不知道如何操作。 應該是當您單擊播放按鈕時,它會將您帶到 function drawInstructions(將顯示說明的位置),但我無法弄清楚如何在調用 function drawInstructions 時刪除顯示在 canvas 上的播放按鈕。 它只是停留在 canvas 上。

當我嘗試將刪除語法放入 function 設置時,該按鈕甚至在調用 function drawInstructions 之前就從屏幕上消失了。 如果我將它的刪除語法放在 function drawInstructions 中,它會說 playButton 尚未定義。

function preload() {
 title = loadImage("title.png");
  optimaFont = loadFont("Optima-ExtraBlack.otf"); // downloaded font from online
}

function setup() {
  createCanvas(512, 384);
  background(title);

  let red1 = color(237, 39, 36);
  var playButton = createButton("PLAY");
  playButton.mousePressed(drawInstructions);
  playButton.position(212, 299);
  playButton.style("font-family", "Optima bold");
  playButton.style("font-size", "30px");
  playButton.style("background-color", red1);
}

function drawInstructions() {
  background(0);
}

混淆可能源於變量 scope:

  • 如果您的代碼var playButtonsetup()中聲明並使用一個值 ( = createButton...) ) 初始化:這意味着您只能在setup() function 中“看到” playButton ,但不能在外部看到。
  • 您想在稍后階段在不同的 scope 中remove()hide() )按鈕(例如,從drawInstructions() function,當按鈕鼠標按下事件處理程序被觸發時)

您可以在setup()之外聲明var playButton ,從而使其成為全局變量,從 p5 草圖中的任何其他 function 可見,但不要使用值初始化。 playButton將是undefined的,直到您在稍后階段分配一個值)。

您可以在setup()中分配值,您可以在其中調用createButton()

最后,您可以從drawInstructions()訪問playButton (因為現在它是一個全局變量),所以它可以被刪除)。

這是您的代碼的調整版本,以說明上述內容:

 var playButton; function preload() { //title = loadImage("title.png"); //optimaFont = loadFont("Optima-ExtraBlack.otf"); // downloaded font from online } function setup() { createCanvas(512, 384); //background(title); let red1 = color(237, 39, 36); playButton = createButton("PLAY"); playButton.mousePressed(drawInstructions); playButton.position(212, 299); playButton.style("font-family", "Optima bold"); playButton.style("font-size", "30px"); playButton.style("background-color", red1); } function drawInstructions() { background(0); playButton.remove(); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.2/p5.min.js"></script>

請注意,我已經注釋掉了資產加載,因此運行該代碼段很容易。(您應該看到按鈕和白色背景而不是您的圖像,然后是黑色背景(並且沒有按鈕,因為它被刪除了))。

(稍微偏離主題,如果您熟悉使用 p5 庫,您可能會發現p5.SceneManager很有用)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM