You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在p5.js中冻结画布?加载页面后固定显示随机矩形

Fixing Your p5.js Canvas to "Freeze" Random Rectangles

Hey there! Let's get those random rectangles to stay put instead of refreshing non-stop every frame. Here are two simple, effective ways to make that happen:

Option 1: Move All Drawing Logic to setup()

Since setup() only runs once when your sketch loads, this is the most straightforward approach if you don't need any additional animation later. Just move your background and rectangle drawing code into setup()—you can even skip the draw() function entirely:

function setup() { 
  createCanvas(500, 250); 
  background(50, 50, 150); 
  translate(10, 10); 
  for (let i = 0; i < 30; i++) { 
    rect(i*15, 0, 10, random(30, 120)); 
  } 
} 
// No need for draw() here—all rendering happens once in setup
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/p5.min.js"></script>

Option 2: Use noLoop() to Stop the draw() Cycle

If you prefer to keep your code in draw() (maybe you want to restart the animation later with loop()), just add noLoop() at the end of the draw() function. This tells p5.js to run draw() exactly once and then stop:

function setup() { 
  createCanvas(500, 250); 
} 
function draw() { 
  background(50, 50, 150); 
  translate(10, 10); 
  for (let i = 0; i < 30; i++) { 
    rect(i*15, 0, 10, random(30, 120)); 
  } 
  noLoop(); // Stops the draw() loop after the first run
} 
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/p5.min.js"></script>

Quick Note on Both Methods

  • Option 1 is perfect for static sketches where you don't need any updates after the initial load.
  • Option 2 gives you flexibility: if you ever want to refresh the rectangles (like on a button click), you can call loop() again to restart the draw() cycle temporarily.

内容的提问来源于stack exchange,提问作者Anatole Lucet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:21:51