p5 resize window 不清除背景

p5 resize window without clearing the background

以下代码使用 p5dom 插件将 canvas 定位在 window 的中心。要动态调整 canvas 的大小,我使用 windowResized() 函数。我想在设置中保留后台功能。如何在调整 window 大小时防止背景颜色被清除?非常感谢。

var cnv;

function centerCanvas() {
  var x = (windowWidth - width) / 2;
  var y = (windowHeight - height) / 2;
  cnv.position(x, y);
}

function setup() {
  cnv = createCanvas(windowWidth,windowHeight);
  centerCanvas();
  background(255, 0, 200);
}

function draw(){

}

function windowResized() {
  centerCanvas();
  resizeCanvas(windowWidth,windowHeight)
}

您可能会做的一件事是将所有内容绘制到缓冲区而不是直接绘制到屏幕。 createGraphics() 函数是你的朋友。来自 the P5.js reference:

var pg;
function setup() {
  createCanvas(100, 100);
  pg = createGraphics(100, 100);
}
function draw() {
  background(200);
  pg.background(100);
  pg.noStroke();
  pg.ellipse(pg.width/2, pg.height/2, 50, 50);
  image(pg, 50, 50);
  image(pg, 0, 0, 50, 50);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.16/p5.js"></script>

您可能希望将所有内容都绘制到缓冲区中,然后在调整屏幕大小时重新绘制该缓冲区。

画一个也加背景功能就可以了

试试这个:

var cnv;

function centerCanvas() {
  var x = (windowWidth - width) / 2;
  var y = (windowHeight - height) / 2;
  cnv.position(x, y);
}

function setup() {
  cnv = createCanvas(windowWidth,windowHeight);
  centerCanvas();
  background(255, 0, 200);
}

function draw(){
  //HERE:
  background(255, 0, 200);
}

function windowResized() {
  //(you can add it here too...)
  centerCanvas();
  resizeCanvas(windowWidth,windowHeight);
}

另一种方法是,您可以使用 CSS 来编辑尺寸,方法类似于以下内容:

<style>
    canvas {
      width: 100%;
      height: 100%;
    }
</style>

我会简单地在 windowResized 函数中设置背景。

function windowResized() {
  centerCanvas();
  resizeCanvas(windowWidth,windowHeight)
  background(255, 0, 200);
}