Resize the shape, extend the filling gradient

I have a rect with an arbitrary gradient. I want to resize the rect, but not the gradient, i.e. let the gradient extend beyond original rect bounds into new bounds.

For example, from A to B, but not X (which is simply resizing the rect)

What is the technique to achieve this?

Related: can a gradient be recreated on another shape exactly, in canvas coordinates, not in coordinates relative to the shape?