p5.js - p5.js - p5调整窗口大小而不清除背景

我使用windowResized()函数动态调整画布大小,如何在调整窗口大小时防止背景颜色被清除? 多谢。


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()函数是你的朋友,来自P5.js参考


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);


}



...