Skip to content

Instantly share code, notes, and snippets.

@HugoLnx
Created January 10, 2013 12:19
Show Gist options
  • Select an option

  • Save HugoLnx/4501608 to your computer and use it in GitHub Desktop.

Select an option

Save HugoLnx/4501608 to your computer and use it in GitHub Desktop.
Algoritmo que recebe 2 cores hexadecimais e que desenha o gradiente entre as duas usando canvas do HTML5.
<html>
<body>
<fieldset>
<input id="cor1" type="color" />
<input id="cor2" type="color" />
<button id="btn">Gradiente!</button>
</fieldset>
<canvas id="canvas"></canvas>
<script>
var in1 = document.getElementById("cor1");
var in2 = document.getElementById("cor2");
var btn = document.getElementById("btn");
var canvas = document.getElementById("canvas");
canvas.style.width = "500px";
canvas.style.height = "500px"
var ctx = canvas.getContext('2d');
btn.onclick = function(event) {
ctx.clearRect(0,0,canvas.width,canvas.height);
var hex1 = in1.value;
var hex2 = in2.value;
var gradiente = Gradiente.fromHex(hex1, hex2);
for(var i=0; i <= canvas.height; i++) {
var porcentagem = i / canvas.height;
var cor = gradiente.at(porcentagem);
ctx.fillStyle = cor.hex();
ctx.fillRect(0, i , canvas.width, 1);
}
};
function Gradiente(cor1, cor2) {
this.at = function(porc) {
var red = transicao(cor1.red(), cor2.red(), porc);
var green = transicao(cor1.green(), cor2.green(), porc);
var blue = transicao(cor1.blue(), cor2.blue(), porc);
return new Cor(red, green, blue);
};
function transicao(n1, n2, porc) {
return parseInt(n2 + (n1 - n2) * porc);
}
}
Gradiente.fromHex = function(hex1, hex2) {
return new Gradiente(Cor.fromHex(hex1), Cor.fromHex(hex2));
};
function Cor(red, green, blue) {
this.red = function(){return red};
this.green = function(){return green};
this.blue = function(){return blue};
this.hex = function() {
return "#" + toHex(red) + toHex(green) + toHex(blue);
};
function toHex(n) {
var hex = n.toString(16);
if(hex.length === 1) {
return "0" + hex;
}
return hex;
}
}
Cor.fromHex = function(hex) {
var match = hex.match(/[^\#]{2}/g);
var red = parseInt(match[0],16);
var green = parseInt(match[1],16);
var blue = parseInt(match[2],16);
return new Cor(red, green, blue);
};
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment