Viewport and canvas transforms¶
Introduction¶
This is an overview of the 2D transforms going on for nodes from themoment they draw their content locally to the time they are drawn ontothe screen. This overview discusses very low level details of the engine.
Canvas transform¶
As mentioned in the previous tutorial,Canvas layers, everyCanvasItem node (remember that Node2D and Control based nodes useCanvasItem as their common root) will reside in aCanvas Layer. Everycanvas layer has a transform (translation, rotation, scale, etc.) thatcan be accessed as aTransform2D.
Also covered in the previous tutorial, nodes are drawn by default in Layer 0,in the built-in canvas. To put nodes in a different layer, aCanvasLayer node can be used.
Global canvas transform¶
Viewports also have a Global Canvas transform (also aTransform2D). This is the master transform andaffects all individualCanvas Layer transforms. Generally, thistransform is not of much use, but is used in the CanvasItem Editorin Godot's editor.
Stretch transform¶
Finally, viewports have aStretch Transform, which is used whenresizing or stretching the screen. This transform is used internally (asdescribed inMultiple resolutions), but can also be manually seton each viewport.
Input events received in theMainLoop._input_event()callback are multiplied by this transform but lack the ones above. Toconvert InputEvent coordinates to local CanvasItem coordinates, theCanvasItem.make_input_local()function was added for convenience.
Transform order¶
For a coordinate in CanvasItem local properties to become an actualscreen coordinate, the following chain of transforms must be applied:

Transform functions¶
Obtaining each transform can be achieved with the following functions:
Type | Transform |
|---|---|
CanvasItem | |
CanvasLayer | |
CanvasLayer+GlobalCanvas+Stretch |
Finally, then, to convert a CanvasItem local coordinates to screencoordinates, just multiply in the following order:
varscreen_coord=get_viewport_transform()*(get_global_transform()*local_pos)
varscreenCord=(GetViewportTransform()*GetGlobalTransform()).Xform(localPos);
Keep in mind, however, that it is generally not desired to work withscreen coordinates. The recommended approach is to simply work in Canvascoordinates (CanvasItem.get_global_transform()), to allow automaticscreen resolution resizing to work properly.
Feeding custom input events¶
It is often desired to feed custom input events to the scene tree. Withthe above knowledge, to correctly do this, it must be done the followingway:
varlocal_pos=Vector2(10,20)# local to Control/Node2Dvarie=InputEventMouseButton.new()ie.button_index=BUTTON_LEFTie.position=get_viewport_transform()*(get_global_transform()*local_pos)get_tree().input_event(ie)
varlocalPos=newVector2(10,20);// local to Control/Node2Dvarie=newInputEventMouseButton();ie.ButtonIndex=(int)ButtonList.Left;ie.Position=(GetViewportTransform()*GetGlobalTransform()).Xform(localPos);GetTree().InputEvent(ie);