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

สร้างสีระหว่าง #CCCCCC และ #3B5998 สำหรับ color meter ด้วย JavaScript


เราต้องเขียนฟังก์ชันที่สร้างสีสุ่มระหว่างสองสีที่กำหนด มาแก้ปัญหานี้เป็นส่วนๆ

  • ขั้นแรก → เขียนฟังก์ชันที่สร้างตัวเลขสุ่มระหว่างสองตัวเลขที่กำหนด

  • ขั้นที่สอง → แทนที่จะใช้สเกล hex สำหรับสร้างสีสุ่ม เราจะแมป hex ไปเป็นสเกลทศนิยม 0 ถึง 15 และใช้แทน

  • ขั้นสุดท้าย → วนลูปผ่านสตริงสีใดก็ได้ที่กำหนดและสร้างสีสุ่ม

ตัวอย่าง

const randomBetween = (a, b) => {    const max = Math.max(a, b);    const min = Math.min(a, b);    return Math.floor(Math.random() * (max - min) + min); }; const randomColor = (firstColor, secondColor) => {    first = firstColor.toUpperCase().substring(1, secondColor.length);    second = secondColor.toUpperCase().substring(1, firstColor.length);    const scale = '0123456789ABCDEF';    let color = '#';    for(let i = 0; i < first.length && i < second.length; i++ ){       const random = randomBetween(scale.indexOf(first[i]),       scale.indexOf(second[i]));       color += scale[random];    };    return color; }; console.log(randomColor('#34324a', '#42342c')); console.log(randomColor('#f43250', '#12342c')); console.log(randomColor('#34324a', '#47942c')); console.log(randomColor('#ffffff', '#000000'));

ผลลัพธ์ที่เป็นไปได้ในคอนโซลคือ

หมายเหตุ − นี้เป็นเพียงหนึ่งในหลายผลลัพธ์ที่เป็นไปได้ เนื่องจากผลลัพธ์เป็นสุ่มทุกครั้ง

ผลลัพธ์

#33332A #C23328 #36822B #35102A