I'm trying to dynamically create a Viewport, render to it, fetch its contents (as a texture), and discard it again. As a basic test I'm using this script attached to a plain Node2D root node (nothing else in the scene tree):
extends Node2D
func _ready():
# Create viewport
var viewport = Viewport.new()
viewport.size = Vector2(200, 200)
# Create some test content
var rect = ColorRect.new()
rect.color = Color(1, 0, 0)
rect.rect_size = Vector2(100, 100)
# Add to scene
viewport.add_child(rect)
add_child(viewport)
# Wait for content
yield(get_tree(), "idle_frame")
yield(get_tree(), "idle_frame")
# Fetch viewport content
var texture = viewport.get_texture()
var image = texture.get_data()
image.save_png("test.png") # just as a debugging check
This works in the sense that the I do get a "test.png" output file. However, the file is just black -- it looks like nothing has been rendered to the viewport. If I add the test content (the rect) directly as a child it renders fine.
What am I missing that I'm not getting any output from the viewport?