|
355 | 355 | ],
|
356 | 356 | "tags": ["javascript", "utility", "throttle", "performance"],
|
357 | 357 | "author": "dostonnabotov"
|
358 |
| - } |
| 358 | + }, |
| 359 | + { |
| 360 | + "title": "Get Contrast Color", |
| 361 | + "description": "Returns either black or white text color based on the brightness of the provided hex color.", |
| 362 | + "code": [ |
| 363 | + "const getContrastColor = (hexColor) => {", |
| 364 | + " // Expand short hex color to full format", |
| 365 | + " if (hexColor.length === 4) {", |
| 366 | + " hexColor = `#${hexColor[1]}${hexColor[1]}${hexColor[2]}${hexColor[2]}${hexColor[3]}${hexColor[3]}`;", |
| 367 | + " }", |
| 368 | + " const r = parseInt(hexColor.slice(1, 3), 16);", |
| 369 | + " const g = parseInt(hexColor.slice(3, 5), 16);", |
| 370 | + " const b = parseInt(hexColor.slice(5, 7), 16);", |
| 371 | + " const brightness = (r * 299 + g * 587 + b * 114) / 1000;", |
| 372 | + " return brightness >= 128 ? \"#000000\" : \"#FFFFFF\";", |
| 373 | + "};", |
| 374 | + "", |
| 375 | + "// Usage:", |
| 376 | + "console.log(getContrastColor('#fff')); // Output: #000000 (black)", |
| 377 | + "console.log(getContrastColor('#123456')); // Output: #FFFFFF (white)", |
| 378 | + "console.log(getContrastColor('#ff6347')); // Output: #000000 (black)", |
| 379 | + "console.log(getContrastColor('#f4f')); // Output: #000000 (black)" |
| 380 | + ], |
| 381 | + "tags": ["color", "hex", "contrast", "brightness", "utility"], |
| 382 | + "author": "yaya12085" |
| 383 | +} |
| 384 | + |
359 | 385 | ]
|
360 | 386 | },
|
361 | 387 | {
|
|
0 commit comments