xxxxxxxxxx
79
//Demonstrates the suncalc library, which gives various sun and moon times and positions
//https://github.com/mourner/suncalc
//Makesure suncalc.js is included in index.
//There are lots of sunrise and sunset times - e.g. nautical twilight
let now, times;
function setup() {
createCanvas(600,600);
now = new Date();
textSize(20);
textFont("Helvetica");
noLoop();
noStroke();
}
function draw() {
background(32);
// get today's sunlight times for NYC
let times = SunCalc.getTimes(now, 41, -74); //~lat long of nyc
//to the console:
console.log(now);
// format sunrise time from the Date object
console.log(
"Sunrise: " + times.sunrise.getHours() + ":" + times.sunrise.getMinutes()
);
console.log(
"Sunset: " + times.sunset.getHours() + ":" + times.sunset.getMinutes()
);
//To the screen:
let textX = 10,
textY = 30,
textStep = 20;
fill(200, 2255, 220);
text(now, textX, textY+=textStep);
//Some of the sun info (there's a lot more)
fill(255, 180, 32); //sunish color
text("Sunrise: " + dateString(times.sunrise), textX, textY+=textStep);
text("Solar noon: " + dateString(times.solarNoon), textX, textY+=textStep);
text("Sunset: " + dateString(times.sunset), textX, textY+=textStep);
//Some of the moon data. TODO - handle when moon event falls outside of current day
let moonTimes = SunCalc.getMoonTimes(now, 41, -74); //~lat long of nyc
let moonIllumination = SunCalc.getMoonIllumination(now);
print(moonIllumination);
fill(120, 180, 255); //moonish color
text("Moonrise: " + dateString(moonTimes.rise), textX, textY+=textStep);
text("Moonset: " + dateString(moonTimes.set), textX, textY+=textStep);
text("Moonphase: " + nf (moonIllumination.phase, 0,3), textX, textY+=textStep);
//note phase reported as 0-1 with .5 being full moon. NOT % illuminated
}
function dateString(d) {
return d.getHours() + ":" + nf(d.getMinutes(), 2, 0);
}
//convert hours:minutes to decimal
function decimalTime(t) {
return t.getHours() + t.getMinutes() / 60; //could add seconds
}
//toggle 'playback' with space bar, +- one day with right/left arrows
function keyPressed() {
if (keyCode === LEFT_ARROW) {
now.setDate(now.getDate() - 1);
draw();
} else if (keyCode === RIGHT_ARROW) {
now.setDate(now.getDate() + 1);
draw();
} else if (key == "n") {
now = new Date();
draw();
}
}