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?
load-imageloads an image asynchronously, so the reason it's not working in your second example is because the image hasn't been loaded yet whendrawgets called. You can check this by branching using theloaded?function before the call toimage:Running the above code, you'll see a circle being drawn, since
imghasn't been loaded yet. You don't get a Null Pointer Exception either, sinceload-imagehasn't returnednil- it just didn't finish loading the image beforedrawwas 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).setupgets executed beforedraw, which guarantees that images will already be loaded whendrawgets called.