Trying to get responsive window and shapes using p5.js Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Trying to get responsive window and shapes using p5.js without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I’m making my way through JavaScript tutorials (using p5.js) and was interested in coding a responsive screen with four shapes that scale down and stick next to each other while doing so.

Is defining a separate variable for y enough, or would it be better to redefine all the shapes by a new set of x and y variables? Window height/width seems like it should be the correct code to use.

My code:

function setup() {
  createCanvas(window.innerWidth, window.innerHeight);

function draw() {

  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
  rect(0, 0, labelw, labelh)
  text("Test LabelnTestIdeo, 19xx-20xx",0, 0, 200, 200);
<script src=""></script>


You need to do two things:

First, you need to detect when the screen is resized, and resize the canvas when that happens. The windowResized() and resizeCanvas() functions come in handy for that. See the reference for more info.

Second, you just need to use the width and height variables to draw your shapes. The width and height variables are automatically updated when you resize the canvas.

Putting it all together, it would look like this:

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);
We are here to answer your question about Trying to get responsive window and shapes using p5.js - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji