Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

JavaScript - สร้างสีตรงข้าม (Complementary Colors)


เราต้องเขียนฟังก์ชัน JavaScript ที่รับรหัสสี hex เป็นอินพุตเพียงอย่างเดียว

ฟังก์ชันควรหาสีตรงข้าม (complementary color) สำหรับสีที่รับเข้ามา

นี่คือคู่อินพุตและเอาต์พุตบางส่วน

getComplementaryColor('#142814') = '#ebd7eb'; getComplementaryColor('#ffffff') = '#000000'; getComplementaryColor('#3399ff') = '#cc6600';

ตัวอย่างโค้ด

โค้ดสำหรับการทำงานนี้จะเป็นดังนี้

const str1 = '#142814'; const str2 = '#ffffff'; const str3 = '#3399ff'; 
const getComplementaryColor = (color = '') => { 
  const colorPart = color.slice(1); 
  const ind = parseInt(colorPart, 16); 
  let iter = ((1 << 4 * colorPart.length) - 1 - ind).toString(16); 
  while (iter.length < colorPart.length) { 
    iter = '0' + iter; 
  }; 
  return '#' + iter; 
}; 
console.log(getComplementaryColor(str1)); 
console.log(getComplementaryColor(str2)); 
console.log(getComplementaryColor(str3));

ผลลัพธ์

ผลลัพธ์ในคอนโซลจะเป็นดังนี้

#ebd7eb #000000 #cc6600