How to code this?

In my game, the background and foreground image’s dimension are equal to the size of the world.
So I just render them at coordinate 0:0 and achieve desired effect.
Example:

On some games, the background image is smaller than the world. In those cases, the background image is slowly moving when the camera is moving.
Example:

Anyone know how to code it?