I’m using p5’s DOM library to create a div and add links to it. I want the div to show up in the center of the screen (aka the center point of the div should be the same as the center point of the screen). I’m using the center() function on the div but this makes the top right point of the div equal to the center point of the screen, which is not what I want. How can I center the center of the div rather than the top right corner? Thanks!
Well this sounds a bit more like a web development question, and to be honest I am not that well versed in P5. But I do know a bit about centering divs with CSS. What you can do is:
margin-left: auto;
margin-right: auto;
Personally, that is what I do. I also did some searching online and found this:
How to Align A Div, answer from Stack Overflow
Hopefully it helps!
EnhancedLoop7
So, if I’m understanding the code snippet above right…
const sliderX = (p.width - slider.width >> 1) + canv.x,
sliderY = (p.height - slider.height >> 1) + canv.y;
slider.position(sliderX, sliderY);
…in order to center something, you can compute the upper-left coordinate where an element should be drawn in order to be centered by:
- take the corner of the main canvas (
canv.x
) - add half the p5.js canvas width (
p.width/2
, orp.width >> 1
) – that is now the center of the sketch - subtract half the object width (
slider.width/2
orslider.width >> 1
) – that is the x for the upper corner of the object when centered
Do the same thing for heights to get the y as well. That gives you the coordinate of the upper left corner of the object. Now call .position(x, y)
, and put the object there. The object is centered.
Edit: this steps above are a geometric narration – the actual order of operations given in the code: (sketch length - object length) / 2 + canvas offset.
1st subtract both widths/heights. Only then halve that subtraction result. And finally add the canvas offset.
Note: That sketch is using the instance mode approach.
Remove the parameter p for the global mode approach.