p5.js | center() Function
The center() function is used to set the alignment of element into the center either vertically, horizontally, or both, relative to its parent element or according to the body if the element has no parent. If this function does not contain any parameters then the element will align both vertically and horizontally.
Note: This function requires the p5.dom library. So add the following line in the head section of the index.html file.
<script language="javascript" type="text/javascript" src="path/to/p5.dom.js"> </script> |
Syntax:
center( align )
Parameters: This function accepts single parameter align which holds the string ‘vertical’ or ‘horizontal’ to align the element.
Below examples illustrate the center() function in p5.js:
Example 1:
function setup() { // Create canvas of given size createCanvas(1000, 200); // Set background color background('green'); var div = createDiv('').size(200, 70); div.html('Welcome to GeeksforGeeks', true); // Set the position of div into center div.center(); // Set font-size of text div.style('font-size', '24px'); // Set font-color of text div.style('color', 'white'); div.style('border', '1px solid white'); div.style('text-align', 'center'); } |
Output:

Example 2:
function setup() { // Create canvas of given size createCanvas(1000, 200); // Set background color background('green'); // Create an input element var input_val = createInput(''); // Set the attribute and its value input_val.attribute('value', 'Welcome to GeeksforGeeks'); // Set the position of div into center input_val.center(); // Set font-size of text input_val.style('font-size', '24px'); // Set the width of input area input_val.style('width', '300px'); } |
Output:

Recommended Posts:
- How to horizontally center a div using CSS?
- HTML | center Tag
- How to vertically center text with CSS?
- How to make elements float to center?
- How to center a popup window on screen?
- How to make an image center-aligned (vertically & horizontally) inside a bigger div using CSS?
- How to call a function that return another function in JavaScript ?
- How to get the function name from within that function using JavaScript ?
- How to get the function name inside a function in PHP ?
- D3.js | d3.max() function
- PHP | Ds\Map xor() Function
- PHP | Ds\Map put() Function
- D3.js | d3.min() function
- D3.js | d3.map.set() Function
- PHP | pi( ) Function
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



