How are canvas games/advanced animations animated? Is clearRect the only way?

I know this is a very generic and possibly well-explained question but I have trouble understanding this topic.

As far as I know HTML <canvas> requires to clear the canvas or parts of it during animation using clearRect. According to Mozilla there’s no other way

And this is where my mind is blown, because it sounds like a great approach for simple animations, with a lot of static stuff, but only for those. What if I have 10,000 objects on a canvas but I want to animate only one? Also clearRect does not clear objects, but pixels so it’s incredibly easy to remove excessive content, especially if your object is not a rectangle!

Example no. 1 – clearRect removes too much:

Here’s a simple example. The blue ball is supposed to follow your pointer. The point is, in the very first frame I’m running a function called drawRandomRectangles that renders 50 random rectangles. Have you noticed? Nope, because they instantly got removed from the canvas on rerender, because ctx.clearRect(0,0, canvas.width, canvas.height); clears everything, excepting what’s being drawn in the next frame!

See here: https://jsfiddle.net/4kf6xdeL/

Example no. 2 – clearRect removes less (still bad):

I know what was the problem in the first example! The clearRect should affect only the ball, as the ball is only animated when you move the pointer. Replacing ctx.clearRect(0,0, canvas.width, canvas.height) with ctx.clearRect(e.clientX, e.clientY, 25, 25) should solve all my problems!

See here: https://jsfiddle.net/4kf6xdeL/2/

Nope, it does not help! It even creates more issues.

Here’s a gif from a fairly simple RTS based game I used to play:

LWG

Note how much is going on there! It renders +800 units at once and every single unit can have separate animation. How does it work? I’ve looked trough the code and I don’t see many clearRects, also I think it would be nearly impossible to do clearRect here, correct? How are complex animations or games done?

NOTE: I don’t want to use any libs, trying to at least grasp low-level canvas 🙂

Also the game from the gif uses unminified source code, but after examining it I still don’t really get how it renders it all… Note layers of multiple canvases aren’t the answer here as all the games I know, agar.io etc. use just only one canvas as different canvases can’t affect each other.

Thanks for any hints, explanations or just fixing my examples 🙂