Hasta ahora los ejemplos que he visto de creación de gradientes en Javascript no me convencen demasiado ya que, o usan imágenes de fondo con el degradado aplicado en ellas (imágenes que es necesario generar con algún editor o con lenguaje de servidor), o utilizan diferentes métodos de clipeo o división de capas (todo termina en un largo bucle en el que se recorre cada una de las subdivisiones generadas con el fin de aplicarle el color necesario para lograr el gradiente). En especial este último método puede consumir demasiados recursos si la superficie a cubrir es extensa.
Afortunadamente, gracias a la compatibilidad del elemento canvas con todos los navegadores modernos y a los filtros propietarios de Explorer, podemos, de manera crossBrowser, generar gradientes livianos en javascript, con un mínimo consumo de recursos y sin usar imágenes u otros extras.
Veamos algunos ejemplos:
Código utilizado:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Gradientes</title>
<style>
#v,#h,#v2,#h2{ width:500px;height:100px; border:1px solid #000; margin-bottom:2px}
</style>
<script>
function $(x){return document.getElementById(x);}
function css(id,prop){
if(window.getComputedStyle){
return document.defaultView.getComputedStyle($(id),null).getPropertyValue(prop);
}else{
var re = /(-([a-z]){1})/g;
if (prop == 'float') prop = 'styleFloat';
if (re.test(prop)) {
prop = prop.replace(re, function () {
return arguments[2].toUpperCase();
});
}
return $(id).currentStyle[prop] ? $(id).currentStyle[prop] : null;
}
}
function gradiente(idObj,col1,col2,tipo){
if (document.createElement("canvas").getContext) {
/* ---- canvas ---- */
var b1=parseInt(col1.substr(5,2),16);
var g1=parseInt(col1.substr(3,2),16);
var r1=parseInt(col1.substr(1,2),16);
var b2=parseInt(col2.substr(5,2),16);
var g2=parseInt(col2.substr(3,2),16);
var r2=parseInt(col2.substr(1,2),16);
var ref = document.createElement("canvas");
ref.width = parseInt(css(idObj,'width'));
ref.height =parseInt(css(idObj,'height'))
var context = ref.getContext("2d");
context.translate(0,0);
context.scale(1,1);
if(tipo){
context.translate(ref.width,0);
context.rotate(Math.PI/2);
var gradient = context.createLinearGradient(0, 0, 0, ref.width);
gradient.addColorStop(1, "rgba("+r1+","+g1+","+ b1+", 1.0)");
gradient.addColorStop(0, "rgba("+r2+","+g2+","+ b2+", 1.0)");
context.fillStyle = gradient;
context.fillRect(0,0,ref.height, ref.width);
}else{
var gradient = context.createLinearGradient(0, 0, 0, ref.height);
gradient.addColorStop(0, "rgba("+r1+","+g1+","+ b1+", 1.0)");
gradient.addColorStop(1, "rgba("+r2+","+g2+","+ b2+", 1.0)");
context.fillStyle = gradient;
context.fillRect(0,0,ref.width, ref.height);
}
$(idObj).appendChild(ref);
} else {
/* ---- DXImageTransform ---- */
$(idObj).style.filter=
"progid:DXImageTransform.Microsoft.Gradient(startColorstr="+col1+", endColorstr="+col2+", GradientType="+tipo+")"
}
}
window.onload=function(){
gradiente('v','#FF0000','#FFFF00',0);
gradiente('h','#00FF00','#FFFF00',1);
gradiente('v2','#663399','#CCFFFF',0);
gradiente('h2','#00FFCC','#CCFFFF',1);
}
</script>
</head>
<body>
<div id="v"></div>
<div id="h"></div>
<div id="v2"></div>
<div id="h2"></div>
</body>
</html>