Reputation:
I am working on an obstacle game, similar to the chrome dinosaur game or geometry dash, and am having some trouble with the CSS.
My first issue: I am trying to center the canvas to the middle of the screen, both horizontally and vertically. Here is my code that works only for full-screen pages:
html, body {
margin: 0;
padding: 0;
align-items: center;
display: flex;
}
canvas {
position: absolute;
top: 25%;
left: 10%;
display: block;
border: 15px solid #edce00;
border-radius: 30px;
align-items: center;
display: flex;
}
Here is what it shows for full-screen pages vs. altered page sizes:
As you can see, the game is not fully visible on a page where the dimensions are adjusted. this leads me to my second problem.
My second issue: I am also trying to set a minimum page size. This way, the whole game screen will be shown, no matter how large or how small (to an extent), the screen is. Is there any way to have the canvas resize itself accordingly to the page size, and make sure it goes no smaller than an "x" amount? Would this be done in Javascript or CSS?
If you could help me with either issue, that would greatly help. Thank you!
Edit: Here is the link to the p5 sketch, if that helps. https://editor.p5js.org/ThisBubblyBoi/sketches/CbxWQSrjF
Upvotes: 3
Views: 630
Reputation: 1328
Unfortunately, if you try to use CSS to resize your canvas element, when you draw on it it will become blurry.
So you have to use Js to set the width
and height
attributes of the canvas. Beware that because of that you will probably have to change the way you draw on the canvas.
let canvas = document.querySelector("#myCanvas");
canvas.width = Math.max(400, canvas.clientWidth);
canvas.height = canvas.clientHeight;
body {
box-sizing: border-box;
display: flex;
align-items: center;
justify-content: center;
margin: 0;
height: 100vh;
width: 100vw;
min-width: 400px;
padding: 60px;
}
canvas {
border: 2px solid yellow;
width: 100%;
height: 100px;
}
<canvas id="myCanvas" width="50" height="50"/>
Notice that if draw on the canvas and then resize it will look blurry with this solution, you just need to refresh the page with the correct resoluton to fix that.
Upvotes: 1