---
# System prepended metadata

title: 顏色相加 - 調色盤
tags: [Example]

---

---
tags: Example,
disqus: hackmd
---

# 顏色相加 - 調色盤

因為想試試HTML API的drag跟drop，於是我想到不然來做一個A色+B色=C色好了。

[先看範例](https://codepen.io/gogorock2001/pen/JjGNMNm?editors=0011)

[我的成品](https://hsiaomingcheng.github.io/react-drag-drop/public/)

因為一個顏色有RGB三色，所以顏色的相加是由兩色的RGB各自相加再除以2。
舉例:把A的R+B的R再/2，就會是C的R

首先一個顏色有RGB所以用迴圈把RGB分別取出，再把他們轉成以16位元為單位的數字，做相加再除2

```javascript=
var c1 = "#FF0000";
var c2 = "#012549";

for(var i = 0; i<3; i++) {
  var sub1 = c1.substring(1+2*i, 3+2*i); //取A色RGB
  var sub2 = c2.substring(1+2*i, 3+2*i); //取B色RGB
  var v1 = parseInt(sub1, 16); //把R G B轉成16位元的數字
  var v2 = parseInt(sub2, 16); //把R G B轉成16位元的數字
  var v = Math.floor((v1 + v2) / 2); //相加再除2
  
  console.log('v', v); //R G B各自相加除2後的值
                       //R = 80, G = 12, B = 24
}
```

再來把RGB這三個數字轉回字串，並轉為大寫，須注意要以16位元轉。
```javascript=
var c1 = "#FF0000";
var c2 = "#012549";

for(var i = 0; i<3; i++) {
  var sub1 = c1.substring(1+2*i, 3+2*i);
  var sub2 = c2.substring(1+2*i, 3+2*i);
  var v1 = parseInt(sub1, 16);
  var v2 = parseInt(sub2, 16);
  var v = Math.floor((v1 + v2) / 2);
  var sub = v.toString(16).toUpperCase(); //轉回字串，並轉為大寫
}
```

這時候只要把，RGB三個字串加一起然後前面加個#就完成了
例： # + '80' + '12' + '24'

但是這裡有一點要注意，就是因為是16位元，有可能轉出來的字串只有一個字
```javascript=
var a = 11;
a.toString(16); // 'b'
```

這樣在最後組合RGB的時候會造成色碼不足的問題，於是要在每個字串的前面+0然後從後面取字串的2位。

```javascript=
var sub = 'b';
('0'+sub).slice(-2); // '0b'
```

這樣一來就大功告成。

```javascript=
var c1 = "#FF0000";
var c2 = "#012549";

var c = "#";
for(var i = 0; i<3; i++) {
  var sub1 = c1.substring(1+2*i, 3+2*i);
  var sub2 = c2.substring(1+2*i, 3+2*i);
  var v1 = parseInt(sub1, 16);
  var v2 = parseInt(sub2, 16);
  var v = Math.floor((v1 + v2) / 2);
  var sub = v.toString(16).toUpperCase();
  var padsub = ('0'+sub).slice(-2);
  c += padsub;
}

document.getElementById("c1").style.backgroundColor = c1;
document.getElementById("c1").innerHTML = c1;
document.getElementById("c2").style.backgroundColor = c2;
document.getElementById("c2").innerHTML = c2;
document.getElementById("c").style.backgroundColor = c;
document.getElementById("c").innerHTML = c;
```

---

文章參考
[How can I get the color halfway between two colors?](https://stackoverflow.com/questions/14482226/how-can-i-get-the-color-halfway-between-two-colors)
[Halfway between two hex color codes](https://www.programming-idioms.org/idiom/154/halfway-between-two-hex-color-codes)