Emitted colors depend on the electronic configuration of the elements involved. Heat energy from the flame excites electrons to a higher quantum level, and the atoms emit characteristic colors (photons with energies corresponding to the visible spectrum) as they return to lower energy levels.
How do the atoms emit the characteristic colors.?
Energy in a photon relates to its wavelength, and wavelength relates to color. Hence, for a given type of atom, the transition between two orbitals (which is set by the nucleus involving physical chemistry matters that are way too complex to spell out here) will always require a certain amount of energy, and the relaxation of an electron between those states will always release a photon of a specific color.