I am attempting to center my sketch but I am having trouble doing so. I want my canvas to take up the entire screen on desktop and mobile and always have my sketch in the middle. What am I missing?
Before, I would just use
function windowResized() {
resizeCanvas(windowWidth, windowHeight)
}
and it would work. I'm guessing this is because of the positioning of my animation, but I have no idea what to do with it.
Here's what I got so far: JS fiddle
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="resources\p5.js"></script>
<script src="resources\p5.dom.js"></script>
<script src="resources\p5.sound.js"></script>
<script type="text/javascript" src="js\app.js"></script>
<link rel="stylesheet" href="css\style.css">
<title>Breathe</title>
</head>
<body>
</body>
</html>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
let outerDiam = 0;
let cnv;
let mySounds = []
function centerCanvas() {
let x = (windowWidth - width) / 2;
let y = (windowHeight - height) / 2;
cnv.position(x, y);
}
function setup() {
cnv = createCanvas(windowWidth, windowHeight);
centerCanvas();
}
function windowResized() {
centerCanvas();
}
function draw() {
background(220);
for (let i = 0; i < 5; i++){
let diam = outerDiam - 30 * i;
if (diam > 0) {
let fade = map(diam, 0, width, 0, 255);
stroke(fade);
noFill();
ellipse(300, 300, diam);
}
}
outerDiam = outerDiam + 2;
}
function mousePressed() {
outerDiam = 0;
}
When you create a canvas, depending on where your js script is doing that in HTML, it will be within the normal HTML flow as a block element(not 100% sure about this, but confident).
Therefore centering the canvas with respect to the viewport should be handled in the parent containing our script, in this case, our HTML file. p5.js's wiki on positioning the canvas offers a solid and concise scenario-based documented solution that is very relevant to you!
When you create the canvas it takes the top-left corner of the canvas as the origin and set's up the coordinate system as shown below
When you create that ellipse it's always going to be in the position 300,300
due to ellipse(300, 300, diam);
. Now the question is how do you center that breathing to the canvas?
There are a few ways!
These are just 2 ways to achieve what you want to do. There's a whole lot more.