This can be achieved by creating a clipping area. The basic idea is that there is a path on the canvas to which the entire drawing is attached.
Make a form and instead of calling stroke() or fill() call clip()
If you do not quite understand how clipping regions work, there are a few.
source share