Nicklas Backstrom had a goal and two assists, and T.J. Oshie, Daniel Winnik and Marcus Johansson had a goal and an assist each for the Capitals. Washington won its 12th straight at home entering its bye week.
Braden Holtby made 18 saves to win his 14th consecutive start, and Washington tied an NHL record by scoring five or more goals in an 11th straight home game.
Ryan Getzlaf had a goal and two assists for the Ducks, who scored twice in the second and twice in the third period to overcome early deficits of 3-0 and 4-1.
John Gibson made 33 saves for Anaheim, which fell to 1-3-1 with one game left on a six-game road trip.
In his 21st career game, the 22-year-old Sanford put the Capitals ahead for good with 2:39 left. He took Brett Connolly's cross-ice pass and unleashed a shot from inside the right faceoff circle that caromed off Gibson's blocker before trickling over the goal line.
Johansson added an empty-net goal with 13 seconds left.
Anaheim closed within two before the second intermission behind goals by Jakob Silfverberg and Hampus Lindholm, then tied it with two goals in just over two minutes midway through the third, both set up by passes from defenseman Cam Fowler.
On the first, Fowler found Ryan Kesler between the faceoff circles for a shot that beat Holtby to his glove side. Then, following a faceoff in the Ducks' end, his outlet feed created a breakaway for Getzlaf, who rounded Holtby and tied it with 8:12 to play.