When we're talking about non-psychedelic drugs there is an important distinction between open and closed eyed hallucinations.
Many drugs can cause closed eyed hallucinations. I get them from alcohol, benzos, gabapentinoids (like lyrica), kratom, opioids, etc.
As to why they occur that's a question for N&P. Honestly probably still unknown to scientists... like asking why we dream.
Open eyed hallucinations (other than basic perceptual distortions, and other from sleep deprivation) are different, a lot more concerning, and generally indicative of psychosis or overdose.