'Scaling' the canvas?

Hello

Is it possible to scale/change the resolution of the canvas in p5.js to create pixel type games? For example, to create a canvas which is 640x640 but will only display 160x160 ‘pixels’ (each being 4x4 actual pixels)?

TIA

Paul

2 Likes

Oh, I think I could do this by drawing to an image then scaling that image up to a larger display canvas. Is that right?

2 Likes

Draw on big image, scale down and display

Or try *0.2 to draw directly

2 Likes

OK thanks, I understand.

2 Likes

Maybe this example can help:

Image:

p5.js code:

let pg;
let pixelSize = 32;
function setup() {
  createCanvas(320, 320);
  pg = createGraphics(width / pixelSize, height / pixelSize);
  pg.ellipseMode(CENTER);
  pg.rectMode(CENTER);
  imageMode(CENTER);
  pg.noStroke();
  noSmooth();
  pg.noSmooth();
  noLoop();
}

function draw() {
  pg.background(255);
  push();
  pg.translate(pg.width / 2, pg.height / 2);
  pg.rotate(QUARTER_PI);
  pg.fill(0);
  pg.rect(0, 0, pg.width / 1.2, pg.height / 1.8);
  pg.fill(255);
  pg.ellipse(0, 0, pg.width / 1.4, pg.height / 2.0);
  pg.fill(0);
  pg.ellipse(0, 0, pg.width / 2.4, pg.height / 3.6);
  image(pg, width / 2, height / 2, pixelSize * pg.width, pixelSize * pg.height);
  pop();
}

EDITED on November 27, 2022 to revise the code slightly and to replace the image.

1 Like

Thanks for the example although I was hoping to avoid having to manually scale each primitive/image.

1 Like

You can make your own functions for all the drawing stuff, you just need to multiply all the input by a certain factor, like this:

function myRect(x1,y1,x2,y2) {
  rect(x1*2,y1*2,x2*2,12*2);
}
1 Like

I am surprised that no one has suggested using the scale() function. In this sketch we define a display 640x640 but use the scale function to change the horizontal and vertical pixel range values to 0- 319 instead of 0 - 639

function setup() {
  createCanvas(640, 640);
  myScale = 2;
  wScaled = width/myScale;
  hScaled = height/myScale;
}


function draw() {
  scale(2, 2); // Makes x and y screen range 0-319
  background(64);
  stroke(255, 0, 0);
  strokeWeight(2);
  fill(255, 200, 200);
  rect(0, 0, wScaled/2, wScaled/2); // Top left quarter
  rect(wScaled/2, hScaled/2, wScaled/2, wScaled/2); // bottom right quarter
  stroke(0,255,0);
  fill(200,255,200);
  ellipse(wScaled/2, hScaled/2, wScaled/6,hScaled/6); // center of display
}
2 Likes