Introduction
Building a basic drawing app is a fun and interactive way to learn graphical programming concepts. This program demonstrates how to create a simple drawing application using Go (Golang) with the github.com/faiface/pixel
library. Users will be able to draw on a canvas with mouse clicks.
Objective
The primary goal of this program is to create a window where users can draw by clicking and dragging the mouse. It introduces fundamental graphics programming techniques using Go and provides a foundation for more advanced graphical applications.
Code
package main import ( "github.com/faiface/pixel" "github.com/faiface/pixel/pixelgl" "golang.org/x/image/colornames" ) func run() { // Create a new window cfg := pixelgl.WindowConfig{ Title: "Basic Drawing App", Bounds: pixel.R(0, 0, 800, 600), VSync: true, } win, err := pixelgl.NewWindow(cfg) if err != nil { panic(err) } // Set the initial background color win.Clear(colornames.White) // Create a slice to store drawn points var points []pixel.Vec for !win.Closed() { // Draw on mouse click and drag if win.Pressed(pixelgl.MouseButtonLeft) { points = append(points, win.MousePosition()) } // Clear the screen and redraw all points win.Clear(colornames.White) for _, point := range points { pixel.NewSprite(nil, pixel.Rect{point, point.Add(pixel.V(2, 2))}).Draw(win, pixel.IM) } // Update the window win.Update() } } func main() { pixelgl.Run(run) }
Explanation
This program utilizes the pixel
library to create a basic drawing application. Here’s how it works:
- Import Libraries: The
pixel
library is used for window creation and rendering, whilecolornames
provides predefined colors. - Initialize Window: A window with a title and size of 800×600 pixels is created.
- Track Mouse Events: When the left mouse button is pressed, the current mouse position is recorded in a slice of points.
- Draw Points: All recorded points are redrawn on each frame, simulating a continuous drawing effect.
- Update Loop: The window updates continuously until it is closed.
How to Run
- Install Go from the official Go website.
- Install the required libraries using:
go get github.com/faiface/pixel go get golang.org/x/image/colornames
- Copy the code into a file named
drawing_app.go
. - Run the program using the command:
go run drawing_app.go
- Interact with the drawing app by clicking and dragging the mouse in the window.