This text cannot be applied to masturbation, because Onan was having sex with a woman at the time, not by himself. In this passage, Onan rebelled against the direct command of his father in Genesis 38:8, "And Judah said unto Onan, Go in unto thy brother's wife, and marry her, and raise up seed to thy brother." Onan displayed contempt towards both his dead brother and his wife. Indeed, this was evil in the eyes of the Lord, "therefore He killed him" (Genesis 38:10).
The whole context is in regard to a man trying to engineer which of his wives will give birth to the first son and thus the heir (Deuteronomy 25:5-6). Onan displeased God in that God did not want his people manipulating His sovereignty. The point is not wasting the "seed," the point is about cruel control of destiny, degrading of the wife, and disobeying a direct command of God.


