Ask Your Question
4

In P5.js, what steps can be taken to resize a grid to match changes in the canvas size?

asked 2023-02-27 11:00:00 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-04-10 19:00:00 +0000

devzero gravatar image

There are a few steps you can take to resize a grid to match changes in the canvas size in P5.js:

  1. Define variables to hold the canvas width and height:
let canvasWidth = 600;
let canvasHeight = 400;
  1. Create a function to handle changes in canvas size:
function windowResized() {
  resizeCanvas(windowWidth, windowHeight);
}
  1. Use the floor() function to calculate the number of rows and columns based on the canvas size:
let numCols = floor(canvasWidth / cellSize);
let numRows = floor(canvasHeight / cellSize);
  1. Use a nested loop to create the grid with the appropriate number of rows and columns:
for (let i = 0; i < numRows; i++) {
  for (let j = 0; j < numCols; j++) {
    // Create cell at (i, j)
  }
}
  1. Update the canvas size in the setup() function:
function setup() {
  createCanvas(canvasWidth, canvasHeight);
  // Create grid
}
  1. Call the windowResized() function whenever the window size changes:
function setup() {
  createCanvas(canvasWidth, canvasHeight);
  // Create grid
  windowResized();
}

function draw() {
  // Draw grid
}

function windowResized() {
  canvasWidth = windowWidth;
  canvasHeight = windowHeight;
  resizeCanvas(canvasWidth, canvasHeight);
  numCols = floor(canvasWidth / cellSize);
  numRows = floor(canvasHeight / cellSize);
}
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-02-27 11:00:00 +0000

Seen: 1 times

Last updated: Apr 10 '22