Zielony Smok - logo witryny

Model RGBA

A albo a dodaje do RGB czwarty składnik ‘alfa’ określający transparentność (przezroczystość, stopień krycia) koloru.

W JavaScript A jest wyrażane jako liczba zmiennoprzecinkowa od 0.0 – 1.0.

Przezroczystość definiujemy dla ścieżki kontekstu jako globalAlpha.

Jeżeli liczba A = 1.0 to kolor RGBA jest identyczny z kolorem RGB.

Kolory RGBA można przedstawić podobnie jak kolory RGB, ale kolor alfa jest wyrażony w postaci liczby zmiennoprzecinkowej od 0.0 do 1.0:

rgba(255, 0, 0, 0.5)

Liczba 0 oznacza przezroczystość zupełną (brak krycia), a liczba 1 – pełną nieprzezroczystość (krycie pełne).

Przeliczanie HEX na RGBA

Listing

// zwraca tablice R,G,B,A gdzie A jest liczbą float pomiedzy 0.0 - 1.0
var HexToRGBA = function(hexa) {
	var R = -1;
	var G = -1;
	var B = -1;
	var A = -1;
	if (((hexa.indexOf("x") == -1) && (hexa.indexOf("#") == -1))) {
		R = parseInt(hexa.substr(0, 2), 16);
		G = parseInt(hexa.substr(2, 2), 16);
		B = parseInt(hexa.substr(4, 2), 16);
		A = parseInt(hexa.substr(6, 2), 16);
	} else {
		if (hexa.indexOf("#") > 0) {
			R = parseInt(hexa.substr(1, 2), 16);
			G = parseInt(hexa.substr(3, 2), 16);
			B = parseInt(hexa.substr(5, 2), 16);
			A = parseInt(hexa.substr(7, 2), 16);
		} else if (hexa.indexOf("x") > 0) {
			R = parseInt(hexa.substr(2, 2), 16);
			G = parseInt(hexa.substr(4, 2), 16);
			B = parseInt(hexa.substr(6, 2), 16);
			A = parseInt(hexa.substr(8, 2), 16);
		}
	}
	return [ R, G, B, Math.roundToDecimal((A - 0.5) / 255, 4) ];
};

Przeliczanie zRGBA na HEX

Listing

// a jest typu float pomiędzy 0.0 - 1.0
var RGBAToHex = function(r, g, b, a) {
	var r1 = parseInt(r).toString(16).toUpperCase();
	var g1 = parseInt(g).toString(16).toUpperCase();
	var b1 = parseInt(b).toString(16).toUpperCase();
	var a1 = parseInt(Math.roundToDecimal(a * 255 + 0.5), 4).toString(16)
			.toUpperCase();
	if (r1.length == 1) {
		r1 = "0" + r1;
	}
	if (g1.length == 1) {
		g1 = "0" + g1;
	}
	if (b1.length == 1) {
		b1 = "0" + b1;
	}
	if (a1.length == 1) {
		a1 = "0" + a1;
	}
	return "0x" + r1 + g1 + b1;
};

Różne wartości krycia

Zawartość możesz zobaczyć w
przeglądarce obsługującej element <canvas>
z kontekstem "2d"

Listing

	var cv = document.getElementById("canvas");
	var ctx = cv.getContext("2d");
	ctx.save();
	ctx.beginPath();
	ctx.rect(10, 20, 100, 100);
	ctx.fillStyle = "green";
	ctx.fill();
	ctx.globalAlpha = 0.6;
	ctx.beginPath();
	ctx.arc(120, 120, 60, 0, 2 * Math.PI, false);
	ctx.fillStyle = "red";
	ctx.fill();
	for (var i = 0; i 7lt; 6; i++) {
		ctx.beginPath();
		ctx.globalAlpha = 0.2 * i;
		ctx.arc(10 + 80 * i, 250, 60, 0, 2 * Math.PI, false);
		ctx.fillStyle = "red";
		ctx.fill();
	}
	ctx.restore()
	ctx.fillStyle = "black";
	ctx.fillText("0.0", 10 + 80 * 0, 300);
	ctx.fillText("0.2", 10 + 80 * 1, 300);
	ctx.fillText("0.4", 10 + 80 * 2, 300);
	ctx.fillText("0.6", 10 + 80 * 3, 300);
	ctx.fillText("0.8", 10 + 80 * 4, 300);
	ctx.fillText("1.0", 10 + 80 * 5, 300);