In game screenshot of specific portion of screen

Godot Version 4.4.1

Question

I want to take in game screen shot of specific area of my screen no matter it is visible to user or not.

Back Ground

I am building a Use-Case UML tool in Godot and After building the diagram i need to save the image of the diagram. For this i need some feature that take that part of canvas and store it as image.

Hint

get_tree().root.get_texture().get_image().save_png(“user://snapshot.png”)

The above code save images but it some only that part of canvas that is visible in the camera not the whole part of image i wanted.

Suggestion

Any Form of suggestion is appreciated. Thank You

Repo Link

GitHub repo

You can do that by creating a new SubViewport and sharing the World2D of your main Viewport with it so it draws the same content as the main Viewport

Something like this should work:

extends Node


func _ready() -> void:
	take_screenshoot()

	
func take_screenshoot() -> void:
	# Create the SubViewport 
	var sub_viewport = SubViewport.new()
	# Add the SubViewport to the tree
	add_child(sub_viewport)
	# Use the same World2D as the main Viewport
	sub_viewport.world_2d = get_viewport().world_2d
	# Set its size
	sub_viewport.size = Vector2(1000, 1000)
	# We only need it to update once for the screenshoot
	sub_viewport.render_target_update_mode = SubViewport.UPDATE_ONCE
	# Move it to the place we want to take the screenshoot
	sub_viewport.canvas_transform.origin = Vector2(-1024, 0)
	# Wait for the next frame to render
	await RenderingServer.frame_post_draw
	# Grab the image, save it and free the SubViewport
	var img = sub_viewport.get_texture().get_image()
	img.save_png("res://screenshot.png")
	sub_viewport.queue_free()
2 Likes

That’s amazing this thing works well. You save me a lot of time.