如何让Canvas铺满窗口宽度?动态设置width1/width2为窗口实际宽度
解决方法:动态获取窗口宽度并适配元素尺寸
核心问题分析
固定值900无法随窗口尺寸变化自动调整,且直接使用100%不符合p5.js的数值逻辑。需通过windowWidth动态计算可用宽度,并同步更新所有依赖该宽度的元素。
代码修改步骤
1. 初始化动态宽度变量
将固定的宽度赋值改为基于窗口尺寸的动态计算(保留左右各25px边距):
let width1; let width2; function setup() { createCanvas(windowWidth, windowHeight); angleMode(DEGREES); // 动态计算可用宽度(窗口宽度减去左右25px边距) width1 = windowWidth - 50; width2 = windowWidth - 50; // ...其余setup代码不变 }
2. 修正粒子生成的X范围
原代码粒子的右边界错误,需改为25 + width2(确保粒子在边距内的可用区域生成):
// 在setup函数的粒子生成循环中 for (let i = 0; i < 1000; i++) { particles.push( new Particle( random(25, 25 + width2), // 修正右边界 random(height1 + 30, height1 + 50 + height2) ) ); }
3. 同步更新窗口resize时的元素
扩展windowResized函数,确保所有依赖宽度的元素随窗口尺寸变化:
function windowResized() { resizeCanvas(windowWidth - 4, windowHeight - 4); // 更新宽度变量 width1 = windowWidth - 50; width2 = windowWidth - 50; // 更新滑块尺寸 slider1.size(width2 - 25); slider2.size(width2 - 25); // 重置磁铁到区域中心 magnet.center.x = 25 + width2 / 2; magnet.center.y = height1 + 50 + height2 / 2 + 20; // 重新生成粒子适配新宽度 particles = []; for (let i = 0; i < 1000; i++) { particles.push( new Particle( random(25, 25 + width2), random(height1 + 30, height1 + 50 + height2) ) ); } // 更新顶部粒子列 cols = floor(width2 / scl) - 2; for (let i = 0; i < cols; i++) { particles.push(new Particle(25 + i * scl, height1 + 50 + 50, true)); } // 更新图表和罗盘位置 graph = new Graph(25, 5, width1, height1); compass = new Compass(25 + width1 - 2, 33); }
4. 修正绘制区域的宽度判断
将草地和泥土的宽度从width - 50改为width2(与动态宽度变量保持一致):
// 在draw函数的绘制草地/泥土部分 push(); noStroke(); fill(0, 190, 0); rect(25, height1 + 50 + 50, width2, 10); //grass fill(205, 92, 8); rect(25, height1 + 50 + 50 + 10, width2, height2 - 50); //earth pop();
5. 修正磁铁拖动的边界逻辑
确保磁铁仅在可用区域内可拖动:
function move() { if ( mouseIsPressed && mouseX > 25 && mouseX < 25 + width2 && // 修正右边界 mouseY > height1 + 110 && mouseY < height1 + height2 + 50 ) { cursor("grab"); magnet.center.x = mouseX; magnet.center.y = mouseY; } else { cursor(); } }
效果说明
修改后,width1和width2会自动适配窗口宽度,所有依赖这两个变量的元素(滑块、粒子、图表、磁铁区域)都会随窗口尺寸变化同步调整,实现全屏适配效果。
内容的提问来源于stack exchange,提问作者Sagar Rawal
相关产品推荐
相关产品推荐

