javascriptRGB颜色转换到16进制详解

快乐打工仔 分类:实例代码

本章节分享一段代码实例,它实现了RGB颜色转换为16进制的功能。

好像在实际应用中,16进制颜色格式的使用远远要比RGB的要多。

代码实例如下:

//颜色转换
var Color = function() {
  if (!(this instanceof Color)) {
   var color = new Color();
   color._init.apply(color, arguments);
   return color;
  }
  if (arguments.length) {
   this._init.apply(this, arguments);
  }
}
//设置get,set方法
var methods = ["red", "green", "blue", "colorValue"];
var defineSetGetMethod = function(fn, methods) {
  var fnPrototype = fn.prototype;
  for (var index = 0; index < methods.length; index++) {
   var methodName = methods[index].charAt(0).toLocaleUpperCase() + methods[index].substring(1);
   fn.prototype['set' + methodName] = new Function("value", "this." + methods[index] + "= value;");
   fn.prototype['get' + methodName] = new Function("return this." + methods[index] + ";");
   fn.prototype['toString'] = new Function('return "rgb("+this.red+","+this.green+","+this.blue+")";');
  }
};
defineSetGetMethod(Color, methods);
//扩展函数的实例方法
var extend = function(fn, option) {
  var fnPrototype = fn.prototype;
  for (var index in option) {
   fnPrototype[index] = option[index];
  }
};
extend(Color, {
  _init : function() {
   if (arguments.length == 3) {
    this.red = arguments[0];
    this.green = arguments[1];
    this.blue = arguments[2];
    this.getColorValue();
   } else {
    var colorValue = arguments[0].replace(/^\#{1}/, "");
    if (colorValue.length == 3) {
     colorValue = colorValue.replace(/(.)/g, '$1$1');
    }
    this.red = parseInt('0x' + colorValue.substring(0, 2), 16);
    this.green = parseInt('0x' + colorValue.substring(2, 4), 16);
    this.blue = parseInt('0x' + colorValue.substring(4), 16);
    this.colorValue = "#" + colorValue;
   }
  },
  getColorValue : function() {
   if (this.colorValue) {
    return this.colorValue;
   }
   var hR = this.red.toString(16);
   var hG = this.green.toString(16);
   var hB = this.blue.toString(16);
   return this.colorValue = "#"
   + (this.red < 16 ? ("0" + hR) : hR) 
   + (this.green < 16 ? ("0" + hG) : hG) 
   + (this.blue < 16 ? ("0" + hB) : hB);
  }
});
var color=new Color();
color.setRed(14);
color.setGreen(124);
color.setBlue(29);
console.log(color.getColorValue());
console.log(Color(12,34,56).getColorValue());
console.log(Color("#fff").getColorValue())
console.log(Color("#defdcd").getColorValue())

上面的代码实现了我们的要求,下面介绍一下它的实现过程。

一.代码注释:

(1).var Color = function() {},创建一个Color构造函数。

(2).if (!(this instanceof Color)) {

  var color = new Color();

  color._init.apply(color, arguments);

  return color;

},判断this是否是Color的对象实例,其实也就是判断是否使用new 运算符来调用Color()

var color = new Color(),创建对象实例。

color._init.apply(color, arguments),调用_init()方法进行对象初始化操作。

return color,返回创建的对象。

其实这个方式和jQuery创建对象的方式是相同的,大家知道创建一个jQuery对象没必要采用new jQuery()的方式,直接使用jQuery("#id")类似于这种方式就可以。这里也是模拟这种方式。

(3).if (arguments.length) {

  this._init.apply(this, arguments);

},这种是采用new的方式来创建一个对象。

(4).var methods = ["red", "green", "blue", "colorValue"],创建一个数组,里面存储了一些关键字,后面会用到。

(5).var defineSetGetMethod = function(fn, methods){},创建一个方法为构造函数添加一些设置或者获取rgb颜色值的方法。

(6).var fnPrototype = fn.prototype,将原型对象赋值给变量fnPrototype。

(7).for (var index = 0; index < methods.length; index++) {},进行遍历操作。

(8).var methodName = methods[index].charAt(0).toLocaleUpperCase() + methods[index].substring(1),如果数组中的当前元素是"red",那么就会被转换为"Red"。

(9).fn.prototype['set' + methodName] = new Function("value", "this." + methods[index] + "= value;"),添加一个新的方法,此方法可以设置RGB颜色中的对应部分的值。

(10).fn.prototype['get' + methodName] = new Function("return this." + methods[index] + ";"),获取RGB颜色中对应部分的值。

(11).fn.prototype['toString'] = new Function('return "rgb("+this.red+","+this.green+","+this.blue+")";'),获取完整的RGB值。

(12).defineSetGetMethod(Color, methods),调用此方法进行相关操作。

(13).var extend = function(fn, option) {

  var fnPrototype = fn.prototype;

  for (var index in option) {

    fnPrototype[index] = option[index];

  }

},此方法可以通过原型扩展对象。

(14).extend(Color, {}),为Color的对象实例扩展了两个方法。

(15). _init : function() {},此方法可以初始化对象实例。

(16).if (arguments.length == 3) {

  this.red = arguments[0];

  this.green = arguments[1];

  this.blue = arguments[2];

  this.getColorValue();

}判断传递的参数是否不是三个,也就是Color(12,34,56)这种RGB形式的。

那么就将对应的R、G和B三个对应的值赋值给对应属性。

最后调用getColorValue()方法。

(17).var colorValue = arguments[0].replace(/^\#{1}/, ""),如果是传递的#fff或者#defdcd形式的参数,那么将#去掉。

(18).if (colorValue.length == 3) {

  colorValue = colorValue.replace(/(.)/g, '$1$1');

},如果字符串的长度等于3,也就是#fff这种形式,那么就会被替换成完整的形式#ffffff。

(19).this.red = parseInt('0x' + colorValue.substring(0, 2), 16),将对应的R值转换为数字(以十进制形式表示的16进制)。

(20).this.colorValue = "#" + colorValue,前面加#返回颜色值。

(21).getColorValue : function() {},返回转换后的值。

(22).if (this.colorValue) {  return this.colorValue;

},判断是否存在colorValue属性,如果存在直接返回即可。

(23).var hR = this.red.toString(16),将对应的R的颜色值转换为16进制。

(24).return this.colorValue = "#" 

  + (this.red < 16 ? ("0" + hR) : hR) 

  + (this.green < 16 ? ("0" + hG) : hG) 

  + (this.blue < 16 ? ("0" + hB) : hB);

}返回最终的转换后的16进制格式颜色。

二.相关阅读:

(1).instanceof可以参阅javascript instanceof一章节。

(2).apply()可以参阅javascript apply()一章节。

(3).arguments可以参阅Javascript arguments对象一章节。

(4).prototype属性可以参阅javascript prototype一章节。

(5).charAt()方法可以参阅javascript String charAt()一章节。

(6).toLocaleUpperCase()方法可以参阅JavaScript toLocaleUpperCase()一章节。

(7).replace()方法可以参阅replace()一章节。

(8).parseInt()方法可以参阅javascript parseInt()一章节。

(9).substring()方法可以参阅substring()一章节。

一线大厂高级前端编写,前端初中阶面试题,帮助初学者应聘,需要联系微信:javadudu

回复

我来回复
  • 暂无回复内容