Search code examples
javascriptcanvasresizep5.jsmouse-coordinates

How to properly resize canvas according to screen size? Javascript (p5.js)


So, as the question says I need to resize the canvas according to screen size. However the thing is that that's not it. I also need to have the mouse coordinates updated proportionally. Seems like I made a fatal mistake of not considering screen sizes from the start since this is my first proper game. I made the game on basis of my 1080p screen. Things like positioning stuff and checking mouse coordinates are all based on a 1920x1080 canvas. Please help!

Github links:

  1. Main game, will work but size will depend on your screen: https://proqbr.github.io/powerdown/
  2. all the files(only 15MB in case you'd like to see by downloading): https://github.com/proqbr/powerdown
  3. sketch.js (pretty much main file regarding this): https://github.com/proqbr/powerdown/blob/master/sketch.js

Main thing is in sketch.js, On lines 260-263 are some createCanvas lines in function setup(), the uncommented one is createCanvas(1920,1080); as it's what i was working with. And on lines 302-314 are a bunch of camera.zoom lines, uncommented one is camera.zoom = 1; since on my screen there was no required zoom for the main menu.

Line 352 onwards is some code on knowing where the player clicked, the problem is this. I do know how to make the canvas's contents look properly resized on all screens by using windowWidth & windowHeight however it's the incorrect mouse coordinates which causes the problem. It would be great if someone could help.

In case there's some problem with the game on your side, here's a quick second video how the game menu works, although it's pretty straightforward anyways: https://youtu.be/eZZw5CmOXEE


Solution

  • I figured it out myself. For some values like when testing if mouseX >= 720 I had to edit it to mouseX >= 785*windowWidth/1920.

    For one translate that I had used, translate(95,525), I had to modify it a little more and this was the one that properly worked translate(displayWidth/2-865*(windowWidth)/1920,displayHeight/2-15*(windowHeight)/1080);

    As for screen resizing this worked fine:

    function windowResized() {
      resizeCanvas(windowWidth, windowHeight);
      if(windowHeight > windowWidth){
        factor = windowHeight;
        factdiv = 1080;
      }else{
        factor = windowWidth;
        factdiv = 1920;
      }
    }
    

    I had to mess around with these to figure out a decent solution

    1. canvas dimensions i.e. 1920, 1080
    2. windowWidth, windowHeight
    3. and also displayWidth, displayHeight

    I have also updated the same in the repository so you can see the final outcome from here: https://proqbr.github.io/powerdown/