尝试使用p5.js获得响应窗口和形状



我正在学习JavaScript教程(使用p5.js),并对编写一个具有四种形状的响应屏幕感兴趣,这些形状可以缩小并紧贴在一起。

为y定义一个单独的变量足够了吗?还是用一组新的x和y变量重新定义所有形状更好?窗口高度/宽度看起来应该是要使用的正确代码。

我的代码:

function setup() {
createCanvas(window.innerWidth, window.innerHeight);
}
function draw() {
background(200);
noStroke();
var labelw = window.innerWidth/8;
var labelh = labelw/4;
var sectionw = window.innerWidth;
var sectionh = window.innerHeight;
// Red
if(window.innerWidth/2 < window.innerHeight){
fill(200, 50, 50);
rect(0, 0, sectionw/2, sectionw/4)
}
// Blue
if(window.innerWidth/2 < window.innerHeight){
fill(50, 50, 200);
rect(sectionw/2, 0, sectionw/2, sectionw/4)
}
// Green
if(window.innerWidth/2 < window.innerHeight){
fill(130, 230, 130);
rect(0, sectionh/2, sectionw/2, sectionw/4)
}
// Purple
if(window.innerWidth/2 < window.innerHeight){
fill(190, 100, 230);
rect(sectionw/2, sectionh/2, sectionw/2, sectionw/4)
}
// label1
fill(50)
rect(0, 0, labelw, labelh)
fill(255);
textSize(labelw/10);
text("Test LabelnTestIdeo, 19xx-20xx",0, 0, 200, 200);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.16/p5.js"></script>
<html>
<head></head>
<body></body>
</html>

您需要做两件事:

首先,您需要检测何时调整屏幕大小,并在发生这种情况时调整画布大小。windowResized()resizeCanvas()函数在这方面派上了用场。有关更多信息,请参阅参考资料。

其次,您只需要使用widthheight变量来绘制形状。调整画布大小时,widthheight变量会自动更新。

把它们放在一起,看起来是这样的:

function setup() {
createCanvas(windowWidth, windowHeight);
} 
function draw() {
fill(255, 0, 0);
rect(0, 0, width/2, height/2);
fill(0, 255, 0);
rect(width/2, 0, width/2, height/2);
fill(0, 0, 255);
rect(0, height/2, width/2, height/2);
fill(255, 255, 0);
rect(width/2, height/2, width/2, height/2);
}
function windowResized() {
resizeCanvas(windowWidth, windowHeight);
}

最新更新