Getting started with turtle graphics
Turtle graphics is one of the simplest ways to draw vector graphics on a canvas. A program controls a turtle: it moves through a two-dimensional world and carries a pen that can leave a line behind it.
The model is easy to grasp, but it can produce an endless variety of two-dimensional graphics. It is a useful way to explore programming, mathematics, and generative art without starting with Cartesian geometry.
Brief history
Turtle graphics was introduced in the 1960s as part of the LOGO programming language. Read more about its history.
What is a turtle?
- A turtle lives and moves on a two-dimensional canvas.
- It can turn and move forward or backward.
- It carries a pen. When the pen is down, its movement draws on the canvas.
Draw with a turtle
Give the turtle a sequence of commands. With PicoTurtle, write a Lua
script in your editor and run it with picoturtle.
Turtle commands usually fall into four groups:
-
Movement. Commands such as
right(degrees)turn the turtle, andforward(distance)move it. -
Pen. Use commands such as
penup(),pendown(),pencolor(color), andpenwidth(width)to control drawing. - State. Ask the turtle about its current position, heading, or pen settings.
- Canvas. Change settings such as the canvas size or background.
Two small programs
Draw a square
This draws a square with 100-pixel sides.
local picoturtle = require "picoturtle"
local t = picoturtle.new()
t:penwidth(1)
t:pencolor("black")
for side = 1, 4 do
t:right(90)
t:forward(100)
end
Draw a circle
A circle can be approximated with many short steps and tiny turns.
local picoturtle = require "picoturtle"
local t = picoturtle.new()
t:penwidth(1)
t:pencolor("black")
for step = 1, 360 do
t:right(1)
t:forward(1)
end