xxxxxxxxxx
107
//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
//Nice visual here: https://github.com/mourner/suncalc
var dayOffset = 0,
diameter = 500;
var advance = false;
var now, times;
var dayColor = "#d0d82f",
nightColor = "#383c59",
twilightColor = "#5670a0",
goldenHourColor = "#a58242";
function setup() {
createCanvas(diameter*1.1, diameter*1.1);
now = new Date();
textSize(12);
textFont('Helvetica');
}
function draw() {
background(200);
// get today's sunlight times for London
var times = SunCalc.getTimes(now, 40, -70); //~lat long of nyc
// 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());
var sunriseDecimal = decimalTime(times.sunrise); //my decimalTime function below, e.g. 6:30=6.5
var sunsetDecimal = decimalTime(times.sunset);
//translate to center of screen and rotate drawing 90 degrees CW so noon = up:
push();
translate(width / 2, height / 2);
rotate(PI / 2);
stroke(180);
fill(180);
ellipse(0, 0, diameter+1, diameter+1);
//arc(width/2, height/2, diameter, diameter, 0, PI);
noStroke();
fill(dayColor);
drawArcSegment(sunriseDecimal, sunsetDecimal);
fill(nightColor);
drawArcSegment(sunsetDecimal, sunriseDecimal);
//goldenhours
var amGH = decimalTime(times.goldenHourEnd);
var pmGH = decimalTime(times.goldenHour);
fill(goldenHourColor);
drawArcSegment(sunriseDecimal, amGH);
drawArcSegment(pmGH, sunsetDecimal);
//dawn/dusk/twilight. There are actually three. The closest to night is astronomical. Suncalc uses different terms e.g. dusk
var dawn = decimalTime(times.nauticalDawn);
var dusk = decimalTime(times.nauticalDusk);
fill(twilightColor);
drawArcSegment(sunsetDecimal, dusk);
drawArcSegment(dawn, sunriseDecimal);
pop();
text(now, 20, 20);
//animate one day per frame:
if (advance) {
now.setDate(now.getDate() + 1)
} else {
noLoop();
}
}
//convert hours:minutes to decimal
function decimalTime(t) {
return t.getHours() + t.getMinutes() / 60; //could add seconds
}
function drawArcSegment(start, end) { //start, end are 0-24.
var startRadians = start / 24.0 * TWO_PI;
var endRadians = end / 24.0 * TWO_PI;
arc(0, 0, diameter, diameter, startRadians, endRadians);
}
//toggle 'playback' with space bar, +- one day with right/left arrows
function keyPressed() {
if (key == ' ') advance = !advance;
if (advance) {
loop();
} else {
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();
}
}
}