Great question – I had to look up the answer (and I’ve learned something new today!)
Chameleons apparently change colour to communicate with others, with camoflage being a secondary use!
They are able to change colour because their outer skin contains cells called chromatophores. these cells contain colour pigments in granules. Changing how the coloured granules are distributed in different cells determines what colour the cells are (and hence the chameleon)
Chameleons have specialized cells, collectively called chromatophores, that lie in layers under their transparent outer skin. The cells in the upper layer, called xanthophores and erythrophores, contain yellow and red pigments respectively. Below these is another layer of cells called iridophores (or guanophores), and they contain the colorless crystalline substance guanine. These reflect amongst others the blue part of incident light. If the upper layer of chromatophores appear mainly yellow, the reflected light becomes green (blue plus yellow). A layer of dark melanin containing melanophores is situated even deeper under the reflective iridophores. The melanophores influence the ‘lightness’ of the reflected light. All these different pigment cells can rapidly relocate their pigments, thereby influencing the color of the chameleon.
Contrary to popular belief, this change of color is not purely an adaptation to the surroundings (although the surroundings play a large part) but also an expression of the physical and physiological condition of the lizard. The skin color is changed under influence of mood, light, and temperature. The skin color also plays an important part in communication and rivalry fights.