December 2023
Intermediate to advanced
242 pages
5h 28m
English
| Recipe 5 | Converting Color Names to Hexadecimal Values with the Canvas Element |
Suppose you’re working on a drawing application that works with hexadecimal (hex) color codes. You want to provide a field that lets users enter a color name to be converted to its hex equivalence automatically.
You need a solution for converting colors into their hex representation.
Create a temporary HTML canvas element, obtain its 2D context, and use the fillStyle property to convert the color:
| | function convertColorToHex(color) { |
| | const canvas = document.createElement("canvas"); |
| | const ctx = canvas.getContext("2d"); |
| | ctx.fillStyle = color; |
| | return ctx.fillStyle.toUpperCase(); |
| | } |
| | |
| |
Read now
Unlock full access