Drawing board shader

This project demonstrates how to draw with mouse on a canvas item using shaders in the Godot game engine. Traditional methods of drawing involve complex, performance-heavy texture operations in GDScript. However, in this project, we use shaders along with self buffering techniques to create a simple drawing tool. You may use this as a foundation to develop a more sophisticated drawing tool with features like changing colors, erasing, etc.

There are two shaders: 1. DrawingBoard, and 2. DrawingBuffer. The code below is only the drawing buffer shader. For more details, refer to the demo project and video tutorial.

Shader code
shader_type canvas_item;

uniform sampler2D _bufferTex;
uniform vec4 _color : source_color = vec4(0.0, 0.0, 0.0, 1.0);
uniform float _width = 3.0;
uniform vec2 _mousePos;
uniform vec2 _prevMousePos;

varying vec2 localPos;

void vertex() {
	localPos = VERTEX;
}

float distanceToSegment( vec2 a, vec2 b, vec2 p )
{
    vec2 pa = p - a, ba = b - a;
    float h = clamp( dot(pa,ba)/dot(ba,ba), 0.0, 1.0 );
    return length( pa - ba*h );
}

void fragment() {
	vec4 bufferColor = texture(_bufferTex, UV);

	vec4 mousePos = vec4(_mousePos, 0.0, 1.0);
    vec4 prevMousePos = vec4(_prevMousePos, 0.0, 1.0);

    float linevalue = 0.0;

    if(prevMousePos.x > -1000.0)
    {
	    float dist = distanceToSegment(mousePos.xy, prevMousePos.xy, VERTEX);
	    if(dist < _width)
	        linevalue += 1.0;
    }

    linevalue = clamp(linevalue, 0.0, 1.0);
    vec4 outColor = mix(bufferColor, vec4(1, 1, 1, 1), linevalue);

	COLOR = outColor;
}
Tags
draw shader, drawing board, mouse draw
The shader code and all code snippets in this post are under MIT license and can be used freely. Images and videos, and assets depicted in those, do not fall under this license. For more info, see our License terms.

More from Sivabalan

3D Hover CanvasItem

Related shaders

far distance water shader (sea shader)

Fire dissolve shader

Pixel Cloud Shader

Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments