March Madness 7 – Background gradient generator
Uncategorized
Add comments
Mar 072010
For today’s March Madness program I wanted to try to do something useful with the canvas tag. I decided it would be nice to be able to programmatically generate a background gradient for a web page based on the time of day. If you’re looking at the site in the morning the colors would be different from afternoon, sunset, midnight, etc. I created a hidden canvas tag to do my work and then used the toDataURL method to pass the resulting image to the body’s CSS. Source is below the fold.
JPLT.Class.create("JPLT.BackgroundGradient",JPLT.Object,
function() {
this.width = 1;
this.height = window.innerHeight;
this.createElement();
this.paint();
this.updatePage();
},
{
gradientColorStops: {
dawn: [0, "#413b45", 0.5, "#8c787a", 0.75, "#c39980", 0.95, "#f3a954", 0.99, "#fecb10", 1, "#f5f700"],
morning: [0, "#2b4965", 1, "#d6b487"],
afternoon: [0, "#1A64BF", 1, "white"],
sunset: [0, "#4a58b9", 0.5, "#9364a8", 0.75, "#d87385", 1, "#ffa297"],
dusk: [0, "#040613", 0.5, "#084b7f", 0.75, "#558bad", 1, "#fbbf81"],
night: [0, "black", 0.5, "#09093b", 1, "#3330fd"],
late: [0, "black", 0.5, "#060553", 1, "#090866"]
},
colors: {
dawn: 'black',
morning: 'black',
afternoon: 'black',
sunset: 'white',
dusk: 'white',
night: 'white',
late: 'white',
},
hours: [ 'late','late','late','late','late','dawn','dawn','dawn','morning','morning','morning','morning',
'afternoon','afternoon','afternoon','afternoon','afternoon','sunset','sunset','dusk','dusk','night',
'night','night' ],
createElement: function() {
this.element = document.createElement("canvas");
this.element.width = this.width;
this.element.height = this.height;
return this.element;
},
context: function() {
return this.element.getContext("2d");
},
getText: function() {
var date = new Date();
var hour = date.getHours();
return this.hours[hour];
},
getColor: function() {
var date = new Date();
var hour = date.getHours();
return this.colors[this.hours[hour]];
},
getGradientColorStops: function() {
var date = new Date();
var hour = date.getHours();
return this.gradientColorStops[this.hours[hour]];
},
paint: function() {
var ctx = this.context();
var gradient = ctx.createLinearGradient(0,0,this.width,this.height);
var colorStops = this.getGradientColorStops();
for (var i=0; i