admin管理员组文章数量:1310315
INSTRUCTIONS
Write a function that takes 2 colors as arguments and returns the average color.
- The parameters will be two 6-digit hexadecimal strings. This does not need to be validated.
- The return value should be a 6-digit hexadecimal string.
- The hexadecimal strings represent colors in RGB, much like in CSS.
- The average color is to be determined by taking the arithmetic mean for each ponent: red, green and blue.
CODE
const avgColor = (str1, str2) => {
return (str1 + str2) / 2
}
QUESTION
Hexadecimal is something like this 0000ff
right?
I'm not sure what it means when I need to take the arithmetic mean for each ponent and lists 3 colors. How do you take an average of strings?
INSTRUCTIONS
Write a function that takes 2 colors as arguments and returns the average color.
- The parameters will be two 6-digit hexadecimal strings. This does not need to be validated.
- The return value should be a 6-digit hexadecimal string.
- The hexadecimal strings represent colors in RGB, much like in CSS.
- The average color is to be determined by taking the arithmetic mean for each ponent: red, green and blue.
CODE
const avgColor = (str1, str2) => {
return (str1 + str2) / 2
}
QUESTION
Hexadecimal is something like this 0000ff
right?
I'm not sure what it means when I need to take the arithmetic mean for each ponent and lists 3 colors. How do you take an average of strings?
Share Improve this question edited Jul 16, 2019 at 20:52 Dave Newton 160k27 gold badges260 silver badges307 bronze badges asked Jul 16, 2019 at 20:40 mph85mph85 1,3564 gold badges21 silver badges44 bronze badges 7- You don't take "an average of strings". You interpret each pair of digits has a number and then do a simple numeric average. – Pointy Commented Jul 16, 2019 at 20:43
- A hexidecimal value isn't a string, it's a base-16 numeric value. – esqew Commented Jul 16, 2019 at 20:43
-
@Pointy sorry, im not understanding.
You interpret each pair of digits has a number
? – mph85 Commented Jul 16, 2019 at 20:53 -
2
(1) Use substring to get each pair of digits. (2) Use
parseInt(v, 16)
to convert each pair of hex digits to a number. (3) Average your numbers. (4) Convert each R, G, and B number back to hex using.toString(16)
– user47589 Commented Jul 16, 2019 at 20:53 -
The parameters will be two 6-digit hexadecimal strings
. So this means not 2 strings but 2 numbers? – mph85 Commented Jul 16, 2019 at 20:53
5 Answers
Reset to default 2Here's a plain JS function:
You have to split the hex string into it's three color ponents before converting them to calculate the mean:
function calcAvg(hex1,hex2) {
//parsed into decimal from hex
//for each color pair
let hexC11 = parseInt(hex1.slice(0,2), 16);
let hexC12 = parseInt(hex1.slice(2,4), 16);
let hexC13 = parseInt(hex1.slice(4,6), 16);
let hexC21 = parseInt(hex2.slice(0,2), 16);
let hexC22 = parseInt(hex2.slice(2,4), 16);
let hexC23 = parseInt(hex2.slice(4,6), 16);
//calculate mean for each color pair
let colorMean1 = (hexC11 + hexC21) / 2;
let colorMean2 = (hexC12 + hexC22) / 2;
let colorMean3 = (hexC13 + hexC23) / 2;
//convert back to hex
let colorMean1Hex = colorMean1.toString(16);
let colorMean2Hex = colorMean2.toString(16);
let colorMean3Hex = colorMean3.toString(16);
//pad hex if needed
if (colorMean1Hex.length == 1)
colorMean1Hex = "0" + colorMean1Hex;
if (colorMean2Hex.length == 1)
colorMean2Hex = "0" + colorMean2Hex;
if (colorMean3Hex.length == 1)
colorMean3Hex = "0" + colorMean3Hex;
//merge color pairs back into one hex color
let avgColor = colorMean1Hex +
colorMean2Hex +
colorMean3Hex;
return avgColor;
}
let avg = calcAvg("999999","777777");
console.log(avg);
You can do it with this snippet:
function avg(a,b){
const regex=/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/ //regular expression to parse string
a=regex.exec(a).slice(1) //create array from string 'a' using regex
b=regex.exec(b).slice(1) //create array from string 'b' using regex
let output=''
for(let i=0;i<3;i++){
const value=Math.floor(
(
parseInt(a[i],16) + //parse decimal from hexadecimal
parseInt(b[i],16) //parse decimal from hexadecimal
)/2 //perform averaging
).toString(16) //convert back to hexadecimal
output += (value.length<2?'0':'') + value //add leading zero if needed
}
return output
}
Hexadecimal is something like this 0000ff right?
Yes.
To elaborate, each two characters of the "hexadecimal string" represents a color in hexadecimal (16 numbers per digit), rather than decimal (10 numbers per digit). So the first two characters represent the Red value of the color, the second two characters represent the Green value of the color, and the last two characters represent the Blue value of the color. Combining these values results in the final color.
To further elaborate, the "ff" hexadecimal value equals 256 as a decimal value. Hexadecimal digits go from 0-9, then continue to a, b, c, d, e, and f, before wrapping around to 0 again, so a hexadecimal "0f" number, would equal 16 in decimal. A hexadecimal "10" number would equal 17 as a decimal value. Counting from 0 to 17 in hexadecimal would look like this:
"00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b", "0c", "0d", "0f", "10".
In order to calculate the average of a hexadecimal string value, you need to:
- Convert the hexadecimal string to integer (something similar to
parseInt('0000ff', 16)
) - Split the color ponents
- Calculate the average value for each color ponent
- Reconstruct the final value from the color ponents
- Convert the result back to hexadecimal string (with padding), you can refer to this question How to convert decimal to hexadecimal in JavaScript .
An example of full code snippet will be something similar to
const avgColor = (str1, str2) => {
// Convert the hexadecimal string to integer
const color1 = parseInt(str1, 16);
const color2 = parseInt(str2, 16);
let avgColor = 0;
for (let i = 0; i < 3; i++) {
// Split the color ponents
p1 = (color1 >> (8 * i)) & 0xff;
p2 = (color2 >> (8 * i)) & 0xff;
// Calculate the average value for each color ponent
let v = parseInt((p1 + p2) / 2) << 8 * i;
// Reconstruct the final value from the color ponents
avgColor += parseInt((p1 + p2) / 2) << 8 * i;
}
return decimalToHex(avgColor, 6);
}
// Reference from https://stackoverflow./questions/57803/how-to-convert-decimal-to-hexadecimal-in-javascript
function decimalToHex(d, padding) {
var hex = Number(d).toString(16);
padding = typeof (padding) === "undefined" || padding === null ? padding = 2 : padding;
while (hex.length < padding) {
hex = "0" + hex;
}
return hex;
}
console.log(avgColor("0000ff", "ff0000"))
There is a jQuery plugin for this if you can use jQuery -
$.xcolor.average(color, color)
本文标签: javascriptFinding average of colorshexadecimal stringsStack Overflow
版权声明:本文标题:javascript - Finding average of colors? - hexadecimal strings - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741824015a2399537.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论