Some Practical Clojure Examples
← prev | next →     Top-level ToC     /drawing-with-quil.html     (printable version)

Quil is for drawing static or animated pictures programmatically with Clojure. The default setup allows you to do so interactively from the repl, though you can also create a standalone app.

To get started, do this:

lein new quil my-drawing
cd my-drawing

For me, as of 2015-06-04, the project.clj says we’ll use Clojure 1.8.0 and Quil 2.4.0.

Look in src/my_drawing/core.clj to see something like:

(ns my-drawing.core ...)

(defn setup [] ...)             ; returns a map (your initial state)
(defn update-state [state] ...) ; returns a map (your updated state)
(defn draw-state   [state] ...)

(q/defsketch my-drawing ...)

Do:

$ lein repl
user=> (require 'my-drawing.core)
;; Window pops up running the default demo code.
;;
;; Edit src/my_drawing/core.clj
;;
;; close window, then
user=> (require 'my-drawing.core :reload)

which opens the window again, but with your changes.

That is, when quil.core/defsketch is evaluated, it opens the window and begins drawing.

setup returns initial state (a map). State is automatically passed to update-state and draw-state for you. update-state must return an updated state.

Note though, that that’s using the “functional-mode” that quil supports via quil.middleware/fun-mode, which is what the default for lein new quil my-drawing apps.

Coordinates go:

0
 +---------> x
 |
 |
 |
 V
 y

When you draw, quil doesn’t erase the screen unless you tell it to (see below). So, each time through the draw function, it just draws on top of what’s already there.

If you want to erase (or paint over) the screen and start from a clean slate, call (background some-color). You can put this into your draw-state function if you want to start from scratch each time through.

I think, by default, quil is single-buffered.

func name what it means
background background-color
stroke stroke-color
fill fill-color
stroke-weight stroke-thickness

When you draw an ellipse, the x-y coords you provide are for the center of it.

quil comes with the q/height function which returns the screen height, and also q/width.

See the full Quil API docs online.