Last active
January 3, 2024 18:23
-
-
Save kasthor/da23d1ed802a1eab7ac354305608f40f to your computer and use it in GitHub Desktop.
Minimum code to draw an image to screen in Godot
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extends Node2D | |
var image | |
var should_update_canvas = false | |
var drawing = false | |
# Called when the node enters the scene tree for the first time. | |
func _ready(): | |
create_image() | |
update_texture() | |
$Sprite.offset = Vector2(image.get_width() / 2, image.get_height() / 2) | |
func create_image(): | |
image = Image.new() | |
image.create(500, 500, false, Image.FORMAT_RGBA8) | |
image.fill(Color.white) | |
func update_texture(): | |
var texture = ImageTexture.new() | |
texture.create_from_image(image) | |
$Sprite.set_texture(texture) | |
should_update_canvas = false | |
func _input(event): | |
if event is InputEventMouseButton: | |
drawing = event.pressed | |
if event is InputEventMouseMotion and drawing: | |
image.lock() | |
image.set_pixel(event.position.x, event.position.y, Color.black) | |
should_update_canvas = true | |
image.unlock() | |
func _process(delta): | |
if should_update_canvas: | |
update_texture() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[gd_scene load_steps=2 format=2] | |
[ext_resource path="res://src/Main.gd" type="Script" id=1] | |
[node name="Main" type="Node2D"] | |
script = ExtResource( 1 ) | |
[node name="Sprite" type="Sprite" parent="."] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment