RacketGraphics2htdp/imageVisual-Programming

Creating Graphics in Racket: A Visual Guide | Racket Examples

3.6 min read
Md Nasim SheikhMd Nasim Sheikh
Share:

One of Racket's coolest features is how easily it handles images. Unlike other languages where drawing a circle requires efficient boilerplate, Racket treats images as values—just like numbers or strings.

Advertisement

The 2htdp/image Library

We'll use the 2htdp/image library, designed for the "How to Design Programs" curriculum.

#lang racket
(require 2htdp/image)

Drawing Basic Shapes

Everything is a function!

(circle 30 "solid" "red")
(rectangle 100 50 "outline" "blue")
(text "Hello Racket" 24 "green")

Combinators: Overlay and Above

Since images are values, we can combine them.

Overlay (Stacking on top)

(overlay (circle 20 "solid" "yellow")
         (rectangle 100 100 "solid" "black"))

This puts a yellow circle on top of a black square.

Aside (Side by side)

(beside (circle 30 "solid" "red")
        (circle 30 "solid" "blue")
        (circle 30 "solid" "green"))

Above (Vertical stack)

(above (triangle 40 "solid" "red")
       (rectangle 40 40 "solid" "blue"))

Looks like a little house!

Advertisement

Functional Flowers

Let's use recursion to draw a flower.

(define (petal color)
  (ellipse 20 80 "solid" color))

(define (flower n color)
  (if (= n 0)
      empty-image
      (overlay (rotate (* n 60) (petal color))
               (flower (- n 1) color))))

(flower 6 "purple")

This recursively rotates and overlays 6 petals to create a flower.

Animation (2htdp/universe)

You can even create animations using the universe library.

(require 2htdp/universe)

(define (draw-world t)
  (overlay (circle t "solid" "red")
           (empty-scene 300 300)))

; Animate a growing circle
(animate draw-world)

Summary

Racket turns graphics into a functional programming exercise. By treating images as values that can be composed, rotated, and transformed, you can build complex visualizations with surprisingly little code.

Quick Quiz

Which library provides the standard image primitives in Racket education packs?

Md Nasim Sheikh
Written by

Md Nasim Sheikh

Software Developer at softexForge

Verified Author150+ Projects
Published:

You May Also Like