Quil loading an image to an already created applet

123 Views Asked by At

I'm trying to create a load an image to applet using Clojure Quil library. When I'm storing the load-image reference and use it with image call, during the load it works. But when I do a load and show within draw it is not working.

This works:

(ns img-demo.core
  (:require [quil.core :as q]))

(def img (ref nil))

(def img-url "https://dummyimage.com/100x100/2c3e50/ffffff.png")

(defn setup []
  (q/background 0)
  (dosync (ref-set img (q/load-image img-url))))

(q/defsketch example
  :title "image demo"
  :setup setup
  :draw #(q/image @img 0 0)
  :size [600 600])

This is not working,

(ns img-demo.core
  (:require [quil.core :as q]))

(def img-url "https://dummyimage.com/100x100/2c3e50/ffffff.png")


(q/defsketch example
  :title "image demo"
  :draw #(q/image (q/load-image img-url) 0 0)
  :size [600 600])

In the later case, I understand that load-image should be called inside quil.applet/with-applet. Since it is happening inside defsketch, I expect that to be automatically taken care or at least throw an NPE. Why it is not working?

1

There are 1 best solutions below

0
Count Orlok On

load-image loads an image asynchronously, so the reason it's not working in your second example is because the image hasn't been loaded yet when draw gets called. You can check this by branching using the loaded? function before the call to image:

(q/defsketch example
             :title "image demo"
             :draw #(let [img (q/load-image img-url)]
                      (if (q/loaded? img)
                        (q/image img 0 0)
                        (q/ellipse 100 100 100 100)))
             :size [600 600])

Running the above code, you'll see a circle being drawn, since img hasn't been loaded yet. You don't get a Null Pointer Exception either, since load-image hasn't returned nil - it just didn't finish loading the image before draw was called. As such, all that happens is that nothing is drawn onto the blank canvas.

That's why it's usually recommended to load images in setup (and why your first example works). setup gets executed before draw, which guarantees that images will already be loaded when draw gets called.