DIV CSS 佈局教程網

JavaScript Color 物件:RGB 與十六進位色碼雙向轉換
編輯:JavaScript綜合知識     

做主題化、調色盤或 canvas 繪圖時,經常需要在 rgb(r, g, b) 與 #rrggbb 兩種色碼格式之間來回轉換。與其每次寫一堆 parseInt 與 toString(16),不如封裝成一個 Color 物件。

使用方式

Color(12, 34, 56);   // 傳入三個 RGB 數值
Color("#fff");       // 傳入三位短寫
Color("#defdcd");    // 傳入六位色碼

三種寫法都不需要 new,建構子內部會自行處理。

實現代碼

// 顏色轉換
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 i = 0; i < methods.length; i++) {
    var methodName = methods[i].charAt(0).toLocaleUpperCase() + methods[i].substring(1);
    fn.prototype['set' + methodName] = new Function("value", "this." + methods[i] + "= value;");
    fn.prototype['get' + methodName] = new Function("return this." + methods[i] + ";");
    fn.prototype['toString'] = new Function('return "rgb(" + this.red + "," + this.green + "," + this.blue + ")";');
  }
};
defineSetGetMethod(Color, methods);

// 把物件一次掛到 prototype 上
var extend = function(fn, option) {
  var fnPrototype = fn.prototype;
  for (var i in option) {
    fnPrototype[i] = option[i];
  }
};

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);
  }
});

幾個設計細節

免 new 呼叫

建構子開頭的 if (!(this instanceof Color)) 用來偵測有沒有加 new。沒加時自己補上一個實例並轉交 _init,所以 Color("#fff") 才能正常運作。

三位短寫的展開

#fff 之所以能正確轉成 #ffffff,靠的是 replace(/(.)/g, '$1$1')——把每個字元複製一份。

補零的關鍵

(this.red < 16 ? "0" + hR : hR) 這段是在處理 toString(16) 只吐出一碼的情況。少了它,rgb(0, 0, 5) 會被轉成 #55 這種非法色碼。

快取 colorValue

一旦算出十六進位字串就存回 this.colorValue,下次直接回傳,避免重複計算。

使用範例

var c1 = Color(12, 34, 56);
c1.getColorValue();   // "#0c2238"
c1.toString();        // "rgb(12,34,56)"

var c2 = Color("#defdcd");
c2.getRed();          // 222
c2.getGreen();        // 253
c2.getBlue();         // 205

c2.setRed(0);
c2.getColorValue();   // "#00fdcd"

要注意的是 setRed() 這類 setter 只改了數值卻沒有清掉快取的 colorValue,所以在 setter 中補一行 this.colorValue = null; 會更嚴謹。另外,以 new Function() 動態產生方法雖然示範了「用程式寫程式」的技巧,但會犧牲效能與可讀性,正式專案直接手寫 getter/setter 更好維護。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved