How to make a digital clock in p5.js ?
Last Updated :
08 Mar, 2021
The working of the clock is simple. The current hours, minutes and seconds is retrieved using the hour(), minute() and second() methods. The number returned is then padded with a “0” if it is less than 10 using the formatting function we will create. The AM or PM is determined by using the detected hours value. The whole time string is then displayed as a text using the text() method on the canvas.
Example:
Javascript
function setup() {
createCanvas(480,480);
}
function draw() {
background(0);
strokeWeight(4);
var sec = second();
var min = minute();
var hrs = hour();
var mer = hrs < 12 ? "AM" : "PM" ;
sec = formatting(sec);
min = formatting(min);
hrs = formatting(hrs % 12);
fill(255);
textSize(48);
textAlign(CENTER, CENTER);
text(hrs + ":" + min + ":" + sec +
" " + mer, width/2, height/2);
}
function formatting(num){
if (int(num) < 10) {
return "0" + num;
}
return num;
}
|
Output:
Online Code editor:https://editor.p5js.org/
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...