How can I restrict drawing to the screen to a specific area?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Beamer159

Let’s say I have a Sprite and a custom-drawn line (with draw_line):

Drawn stuff

I want to specify some area, like the area in red, below:

Area to draw in

Then, have these things only appear in the specified area:

Drawn stuff restricted to area

Is there a convenient way to accomplish this?

:bust_in_silhouette: Reply From: Zylann

Control nodes can help doing this.
A Control is a rectangular node and has a clip_content property, which will achieve the effect you want within its rectangle. Control — Godot Engine (3.1) documentation in English
Then everything drawn from it or child of it will be clipped. This is used originally to make scroll areas, but other uses like yours could work too.

If you want to do it from code, another way is with custom drawing in _draw, calling VisualServer:

VisualServer.canvas_item_set_custom_rect(get_canvas_item(), true, your_rect2)
VisualServer.canvas_item_set_clip(get_canvas_item(), true)

This is what Control does in the engine code: