颜色工具类(MOColor) - JS

/ 编程技术 / 没有评论 / 980浏览

代码部分

/**
* MOColor 组件
*/

var MOColor = function() {
	return new MOColor.init();
};

var pt = MOColor.prototype;

MOColor.init = function() {};

MOColor.init.prototype = pt;

/**
 * RGB转整形数字
 * @param {Number} r
 * @param {Number} g
 * @param {Number} b
 */
pt.rgbToInteger = function(r, g, b) {
	r = r & 0xff;
	g = g & 0xff;
	b = b & 0xff;
	return(r << 16) | (g << 8) | b;
};

/**
 * 整形数字转RGB
 * @param {Number} num 值
 */
pt.integerToRgb = function(num) {
	var rgb = {};
	rgb.b = num & 0xff; //B
	rgb.g = num >> 8 & 0xff; //G
	rgb.r = num >> 16 & 0xff; //R
	return rgb;
};

/**
 * ARGB 转 RGB
 * @param {Object} argb ARGB值
 */
pt.argbToRgb = function(argb) {
	return argb & 0xffffff;
};

/**
 * 获得Alpha 值
 * @param {Object} argb 
 */
pt.getAlpha = function(argb) {
	return argb >> 24 & 0xff;
};

/**
 * 不足2位则补0
 * @param {Object} value 值
 */
pt.appendZero = function(value) {
	return value.length == 0 ? "00" : value.length == 1 ? "0" + value : value;
}

/**
 * 转RGB值
 * @param {Object} num
 */
pt.toRgbString = function(num) {
	var rgb = pt.integerToRgb(num);
	var r = pt.appendZero(rgb.r.toString(16));
	var g = pt.appendZero(rgb.g.toString(16));
	var b = pt.appendZero(rgb.b.toString(16));
	return r + g + b;
};

/**
 * 随机颜色
 */
pt.randomColor = function() {
	return Math.floor(Math.random() * 0xffffff);
};

/**
 * 随机带有透明通道的颜色
 */
pt.randomArgbColor = function() {
	return Math.floor(Math.random() * 0xffffffff);
};

/**
 * argb16进制 值 rgb值
 * @param {Object} hexColor
 */
pt.rgbHexToInteger = function(hexColor) {
	return parseInt(hexColor.replace("#", ""), 16);
};

/**
 * 获得随机颜色
 */
pt.getRandomColor = function() {
	var rgb = pt.integerToRgb(pt.randomColor());
	return "rgb(" + rgb.r + "," + rgb.g + "," + rgb.b + ")";
};

/**
 * 获得随机带有透明通道的颜色
 */
pt.getRandomAlphaColor = function() {
	var argb = pt.randomArgbColor();
	var rgb = pt.integerToRgb(argb);
	var alpha = ((pt.getAlpha(argb) / 100) * 0.255).toFixed(3);
	return "rgba(" + rgb.r + "," + rgb.g + "," + rgb.b + "," + alpha + ")";
};

使用方式

var color = new MOColor();

var hexColor = color.toRgbString(color.randomColor());