Main Clojure2d entry point for Canvas, Window and drawing generatively.
Basic concepts:
BufferedImage
java object used to store ARGB color information.Protocols:
clojure2d.pixels
) implement this protocol.Image is BufferedImage
java object. Image can be read from file using load-image
function or saved to file with save
. ImageProto provides get-image
function to access to Image object directly (if you need)
There is no function which creates Image directly (use Canvas instead).
To load SVG use load-svg
which creates internal Batik object. Object can be rendered to Image with transcode-svg
.
Canvas is an object which is used to draw on it. To create new one call canvas
function. Provide width and height and optionally quality hint.
Quality hints are as follows:
:low
- no antialiasing, speed optimized rendering:mid
- antialiasing, speed optimized rendering:high
- antialiasing, quality optimized rendering (default):highest
- as :high
plus PURE_STROKE
hint, which can give strange results in some cases.To draw on Canvas you have to create graphical context. Wrap your code into one of two functions:
with-canvas
- binding macro (with-canvas [local-canvas canvas-object] ...)
with-canvas->
- threading macro (with-canvas-> canvas ...)
.Each function in this macro has to accept Canvas as first parameter and return Canvas.
Canvas bound to Window and accessed via callback drawing function (a'ka Processing draw()
) has graphical context created automatically.
Java2d keyboard and mouse event handlers can be defined as custom multimethods separately for each window. There are following options:
["name" \c]
)
key-pressed
- when key is pressedkey-released
- when key is releasedkey-typed
- when key is typed["name" :key-pressed]
)["name" :mouse-dragged]
)Every event handler accepts as parameters:
Event handler should return new global state.
Window object is responsible for displaying canvas content and processing events. You can also initialize states here.
To create window and display it call show-window
. Function accepts several parameters which are described below.
Window itself simulates workflow which is available in Processing/Quil frameworks.
When window is created following things are done:
:setup
function is provided, call it and use returned value as :draw-state
:fps
, if :draw-fn
is available it's called before refreshment.Additional informations:
:hint
parameter.:refresher
parameter to :fast
.replace-canvas
function.window-active?
function.:draw-state
and :setup
. Value returned by :setup
has a precedence unless is nil
or false
.Following parameters are used:
:canvas
- canvas which is displayed on window. Default is 200x200px:window-name
- name of the window as a string. Used for event multimathods dispatch.:w
- width of the window. Default width of the canvas:h
- height of the window. Default height of the canvas:fps
- frames per second, defaults to 60:draw-fn
- drawing function, called before every display refreshment. Function should accept following four parameters:
with-canvas
or with-canvas->
wrappers.:setup
- setup function which should accept two parameters and return initial draw state.
:state
- initial global state:draw-state
- initial local (drawing) state. If setup
is provided, value returned by it will be used instead.:hint
- display quality hint. Use it when window and canvas have different sizes:refresher
- when create graphical context for draw: :fast
for once or :safe
for each call (default).There are two states managed by library: global state connected to window and draw state connected to callback drawing function.
Each window has its own state kept in atom
. The main idea is to have data which flow between event calls. Every event function accepts state and should return state data.
Initial state can be set with show-window
:state
parameter
To access current state from outside the flow call get-state
. You can also mutate the state with set-state!
.
When drawing callback is used you can keep state between calls. What is returned by callback is passed as a parameter in next call. Drawing function is not synchronized with events that's why local state is introduced. You can still access and change global state.
You can init state from show-window
with :draw-state
or :setup
parameters.
There are plenty of functions which you can use to draw on canvas. They can be grouped to:
point
, rect
, etc.translate
, rotate
, etc.text
, set-font-attributes
, etc.convolve
set-color
, gradient-mode
, set-background
, set-stroke
, etc.All operate on canvas and return canvas as a result. Obviously canvas is mutated.
Session is a datetime with its hash kept globally in vector. To access current session names call session-name
.
Following functions rely on session:
next-filename
- generate unique filename based on sessionlog
- save any information to the file under name based on session. See log-name
.Session is created automatically when needed. Session management functions are:
make-session
- create new sessionensure-session
- create new session when there is no oneclose-session
- close current sessionsession-name
- returns current session.Additional utility functions
to-hex
formatterMain Clojure2d entry point for Canvas, Window and drawing generatively. Basic concepts: * Image - `BufferedImage` java object used to store ARGB color information. * Canvas - Image which contains graphical context. You draw on it. Similar to processing Graphics object. * Window - Window which can display canvas, process events, keeps app/script concept. Similar to Processing sketch with display. * Events - Mouse and keyboard events Protocols: * [[ImageProto]] - basic Image operations (Image, Canvas, Window and Pixels (see [[clojure2d.pixels]]) implement this protocol. * Various events protocols. Events and Window implement these: * [[MouseXYProto]] - mouse position related to Window. * [[MouseButtonProto]] - status of mouse buttons. * [[KeyEventProto]] - keyboard status * [[ModifiersProto]] - status of special keys (Ctrl, Meta, Alt, etc.) * Additionally Window implements [[PressedProto]] in case you want to check in draw loop if your mouse or key is pressed. ## Image Image is `BufferedImage` java object. Image can be read from file using [[load-image]] function or saved to file with [[save]]. ImageProto provides [[get-image]] function to access to Image object directly (if you need) There is no function which creates Image directly (use Canvas instead). ### SVG To load SVG use `load-svg` which creates internal Batik object. Object can be rendered to Image with `transcode-svg`. ## Canvas Canvas is an object which is used to draw on it. To create new one call [[canvas]] function. Provide width and height and optionally quality hint. Quality hints are as follows: * `:low` - no antialiasing, speed optimized rendering * `:mid` - antialiasing, speed optimized rendering * `:high` - antialiasing, quality optimized rendering (default) * `:highest` - as `:high` plus `PURE_STROKE` hint, which can give strange results in some cases. To draw on Canvas you have to create graphical context. Wrap your code into one of two functions: * [[with-canvas]] - binding macro `(with-canvas [local-canvas canvas-object] ...)` * [[with-canvas->]] - threading macro `(with-canvas-> canvas ...)`. Each function in this macro has to accept Canvas as first parameter and return Canvas. Canvas bound to Window and accessed via callback drawing function (a'ka Processing `draw()`) has graphical context created automatically. ## Events Java2d keyboard and mouse event handlers can be defined as custom multimethods separately for each window. There are following options: * Handlers for particular key with dispatch as a vector of window name and key character (eg. `["name" \c]`) * [[key-pressed]] - when key is pressed * [[key-released]] - when key is released * [[key-typed]] - when key is typed * Handler for given key event with dispatch as a vector of window name and key event (eg. `["name" :key-pressed]`) * Handler for mouse event with dispatch as a vector of window name and mouse event (eg. `["name" :mouse-dragged]`) Every event handler accepts as parameters: * Event object (java KeyEvent or MouseEvent) - access to the fields through defined protocols * Global state - state attached to window Event handler should return new global state. ## Window Window object is responsible for displaying canvas content and processing events. You can also initialize states here. To create window and display it call [[show-window]]. Function accepts several parameters which are described below. Window itself simulates workflow which is available in Processing/Quil frameworks. ### Internals When window is created following things are done: 1. Check parameters and create missing values for missed ones. 2. If `:setup` function is provided, call it and use returned value as `:draw-state` 3. Create JFrame, java.awt.Canvas, pack them, attach event handlers and display 4. Set global state 5. Run separated thread which refreshes display with given `:fps`, if `:draw-fn` is available it's called before refreshment. Additional informations: * Display refreshment is done by displaying canvas on JFrame. You can set separate quality hints (same as for canvas) for this process with `:hint` parameter. * When you privide drawing function, it's called every refreshment. By default graphical context is created every call - which costs time but is safe in case you want to directly access pixels. The second variant which can be used is to create graphical context once at the moment of window creation. This variant can be forced by setting `:refresher` parameter to `:fast`. * You can replace canvas attached to window with [[replace-canvas]] function. * Window itself acts as event object (implements all event protocols) * Canvas and window can have different sizes. Display refreshing functions will scale up/down in such case. * Events and refreshment are not synchronized. Try to avoid drawing inside event multimethods. * You can create as many windows as you want. * You can check if window is visible or not with [[window-active?]] function. * If you provide both `:draw-state` and `:setup`. Value returned by `:setup` has a precedence unless is `nil` or `false`. ### Parameters Following parameters are used: * `:canvas` - canvas which is displayed on window. Default is 200x200px * `:window-name` - name of the window as a string. Used for event multimathods dispatch. * `:w` - width of the window. Default width of the canvas * `:h` - height of the window. Default height of the canvas * `:fps` - frames per second, defaults to 60 * `:draw-fn` - drawing function, called before every display refreshment. Function should accept following four parameters: * canvas within graphical context (you don't need to use [[with-canvas]] or [[with-canvas->]] wrappers. * window object * current frame number as a long value * current state * `:setup` - setup function which should accept two parameters and return initial draw state. * canvas withing graphical context * window object * `:state` - initial global state * `:draw-state` - initial local (drawing) state. If `setup` is provided, value returned by it will be used instead. * `:hint` - display quality hint. Use it when window and canvas have different sizes * `:refresher` - when create graphical context for draw: `:fast` for once or `:safe` for each call (default). ## States There are two states managed by library: global state connected to window and draw state connected to callback drawing function. ### Global state Each window has its own state kept in `atom`. The main idea is to have data which flow between event calls. Every event function accepts state and should return state data. Initial state can be set with [[show-window]] `:state` parameter To access current state from outside the flow call [[get-state]]. You can also mutate the state with [[set-state!]]. ### Local state for drawing function When drawing callback is used you can keep state between calls. What is returned by callback is passed as a parameter in next call. Drawing function is not synchronized with events that's why local state is introduced. You can still access and change global state. You can init state from [[show-window]] with `:draw-state` or `:setup` parameters. ## How to draw There are plenty of functions which you can use to draw on canvas. They can be grouped to: * Primitives like [[point]], [[rect]], etc. * Tranformations like [[translate]], [[rotate]], etc. * Text rendering like [[text]], [[set-font-attributes]], etc. * Image manipulations like [[convolve]] * Color and style like [[set-color]], [[gradient-mode]], [[set-background]], [[set-stroke]], etc. All operate on canvas and return canvas as a result. Obviously canvas is mutated. ## Session Session is a datetime with its hash kept globally in vector. To access current session names call [[session-name]]. Following functions rely on session: * [[next-filename]] - generate unique filename based on session * [[log]] - save any information to the file under name based on session. See [[log-name]]. Session is created automatically when needed. Session management functions are: * [[make-session]] - create new session * [[ensure-session]] - create new session when there is no one * [[close-session]] - close current session * [[session-name]] - returns current session. ## Utilities Additional utility functions * date and time functions * [[to-hex]] formatter
Default quality of saved jpg (values: 0.0 (lowest) - 1.0 (highest)
Default quality of saved jpg (values: 0.0 (lowest) - 1.0 (highest)
(alt-gr-down? e)
ALT-GR key state as boolean.
ALT-GR key state as boolean.
(arc canvas x1 y1 w h start extent)
(arc canvas x1 y1 w h start extent type)
(arc canvas x1 y1 w h start extent type stroke?)
Draw arc with middle at (x,y)
position with width w
and height h
.
Starting angle start
and extent
are in radians. Direction is clockwise.
Type is one of the:
:open
:pie
:chord
Draw arc with middle at `(x,y)` position with width `w` and height `h`. Starting angle `start` and `extent` are in radians. Direction is clockwise. Type is one of the: * `:open` * `:pie` * `:chord`
How much processor cores are in system. Constant is machine dependant.
How much processor cores are in system. Constant is machine dependant.
How much intensive tasks can we run. Which is 150% of available cores. Constant is machine dependant.
How much intensive tasks can we run. Which is 150% of available cores. Constant is machine dependant.
(awt-xor-mode canvas c)
Set XOR graphics mode with java.awt.Color
.
To revert call paint-mode
.
Set XOR graphics mode with `java.awt.Color`. To revert call [[paint-mode]].
(bezier canvas x1 y1 x2 y2 x3 y3 x4 y4)
(bezier canvas x1 y1 x2 y2 x3 y3 x4 y4 stroke?)
Draw bezier curve with 4 sets of coordinates.
Draw bezier curve with 4 sets of coordinates.
(black-canvas & r)
Create canvas
with black, opaque background.
Create [[canvas]] with black, opaque background.
(canvas width height)
(canvas width height hint)
(canvas width height hint font)
Create and return Canvas with width
, height
and optionally quality hint name (keyword) and font name.
Default hint is :high
. Default font is system one.
Canvas is an object which keeps everything needed to draw Java2d primitives on it. As a drawing buffer BufferedImage
is used. To draw on Canvas directly wrap your functions with with-canvas
or with-canvas->
macros to create graphical context.
Canvas is transparent by default. See also black-canvas
.
Be aware that drawing on Canvas is single threaded.
Font you set while creating canvas will be default font. You can set another font in the code with set-font
and set-font-attributes
functions. However these set font temporary.
Create and return Canvas with `width`, `height` and optionally quality hint name (keyword) and font name. Default hint is `:high`. Default font is system one. Canvas is an object which keeps everything needed to draw Java2d primitives on it. As a drawing buffer `BufferedImage` is used. To draw on Canvas directly wrap your functions with [[with-canvas]] or [[with-canvas->]] macros to create graphical context. Canvas is transparent by default. See also [[black-canvas]]. Be aware that drawing on Canvas is single threaded. Font you set while creating canvas will be default font. You can set another font in the code with [[set-font]] and [[set-font-attributes]] functions. However these set font temporary.
(char-width canvas chr)
Returns font width from metrics. Should be called within graphical context.
Returns font width from metrics. Should be called within graphical context.
(clip canvas x y w h)
Clip drawing to specified rectangle.
See also reset-clip
.
Clip drawing to specified rectangle. See also [[reset-clip]].
(close-window window)
Close window programmatically
Close window programmatically
(control-down? e)
CONTROL key state as boolean.
CONTROL key state as boolean.
Java ConvolveOp kernels. See convolve
.
Java ConvolveOp kernels. See [[convolve]].
(convolve i kernel)
Convolve with Java ConvolveOp.
Kernel can be predefined as keywords or sequence of numbers (row-wise).
See convolution-matrices
for kernel names.
Convolve with Java ConvolveOp. Kernel can be predefined as keywords or sequence of numbers (row-wise). See [[convolution-matrices]] for kernel names.
(crect canvas x y w h)
(crect canvas x y w h stroke?)
Centered version of rect
.
Centered version of [[rect]].
(curve canvas x1 y1 x2 y2 x3 y3)
(curve canvas x1 y1 x2 y2 x3 y3 stroke?)
Draw quadratic curve with 3 sets of coordinates.
Draw quadratic curve with 3 sets of coordinates.
(datetime)
(datetime type-of-array)
Date time values in the array. Optional parameter :vector or :hashmap (default) to indicate what to return.
Date time values in the array. Optional parameter :vector or :hashmap (default) to indicate what to return.
(double-array-2d sizex sizey)
Create 2d int array getter and setter methods. Array is mutable!
Create 2d int array getter and setter methods. Array is mutable!
(ellipse canvas x1 y1 w h)
(ellipse canvas x1 y1 w h stroke?)
Draw ellipse with middle at (x,y)
position with width w
and height h
.
Draw ellipse with middle at `(x,y)` position with width `w` and height `h`.
(ensure-session)
Ensure that session is active (create one if not)
Ensure that session is active (create one if not)
(file-extension filename)
Extract extension from filename.
Extract extension from filename. * Input: image filename * Returns extension (without dot)
(filled-with-stroke canvas color-filled color-stroke primitive-fn & attrs)
Draw primitive filled and with stroke.
Provide two colors, one for fill (color-filled
), second for stroke (color-stroke
). primitive-fn
is a primitive function and attrs
are function parameters. Do not provide.
One note: current color is replaced with color-stroke
.
Draw primitive filled and with stroke. Provide two colors, one for fill (`color-filled`), second for stroke (`color-stroke`). `primitive-fn` is a primitive function and `attrs` are function parameters. Do not provide. One note: current color is replaced with `color-stroke`.
(flat-hex canvas x y size)
(flat-hex canvas x y size stroke?)
Draw flat topped hex.
Draw flat topped hex.
(flush-graphics canvas)
Dispose current Graphics2D
Do not use directly. Call with-canvas->
or with-canvas
macros.
Dispose current `Graphics2D` Do not use directly. Call [[with-canvas->]] or [[with-canvas]] macros.
(font-ascent canvas)
Returns font width from metrics. Should be called within context.
Returns font width from metrics. Should be called within context.
(font-height canvas)
Returns font width from metrics. Should be called within context.
Returns font width from metrics. Should be called within context.
List of all available font names.
List of all available font names.
(get-canvas window)
Returns canvas bound to window
.
Returns canvas bound to `window`.
(gradient-mode canvas x1 y1 color1 x2 y2 color2)
Set paint mode to gradient.
To revert call paint-mode
Set paint mode to gradient. To revert call [[paint-mode]]
(grid-cell canvas grid x y)
(grid-cell canvas grid x y stroke?)
(grid-cell canvas grid x y scale stroke?)
Draw grid cell for given grid.
Draw grid cell for given grid.
(image canvas img)
(image canvas img x y)
(image canvas img x y w h)
Draw an image.
You can specify position and size of the image. Default it's placed on whole canvas.
Draw an image. You can specify position and size of the image. Default it's placed on whole canvas.
Supported readable image formats. Machine/configuration dependant.
Supported readable image formats. Machine/configuration dependant.
Supported writable image formats. Machine/configuration dependant.
Supported writable image formats. Machine/configuration dependant.
(int-array-2d sizex sizey)
Create 2d int array getter and setter methods. Array is mutable!
Create 2d int array getter and setter methods. Array is mutable!
(inv-transform canvas [x y])
(inv-transform canvas x y)
Inverse transform of given point or coordinates with current transformation. See transform
.
Inverse transform of given point or coordinates with current transformation. See [[transform]].
(key-code e)
Keycode mapped to keyword. See java.awt.event.KeyEvent
documentation. Eg. VK_LEFT
is mapped to :left
.
Keycode mapped to keyword. See `java.awt.event.KeyEvent` documentation. Eg. `VK_LEFT` is mapped to `:left`.
Called on key event
key-event-map
.Should return state.
(defmethod key-event ["My window name" :key-pressed] [event state]
;; do something when 'up' is typed
(when (= :up (key-code event)) (do-something))
state)
Called on key event * Dispatch: vector of window name and key event. See [[key-event-map]]. * Params: key event and current state. Should return state. ``` (defmethod key-event ["My window name" :key-pressed] [event state] ;; do something when 'up' is typed (when (= :up (key-code event)) (do-something)) state) ```
Called when key is pressed.
Should return state.
(defmethod key-pressed ["My window name" \c] [event state]
;; do something when 'c' is pressed
(assoc state :some (calculate-something state)))
Called when key is pressed. * Dispatch: vector of window name and key char * Params: key event and current state. Should return state. ``` (defmethod key-pressed ["My window name" \c] [event state] ;; do something when 'c' is pressed (assoc state :some (calculate-something state))) ```
(key-pressed? w)
Any key pressed? (boolean)
Any key pressed? (boolean)
(key-raw e)
Raw value for pressed key (as integer).
Raw value for pressed key (as integer).
Called when key is released.
Should return state.
(defmethod key-released ["My window name" \c] [event state]
;; do something after 'c' is released
(assoc state :some (calculate-something state)))
Called when key is released. * Dispatch: vector of window name and key char * Params: key event and current state. Should return state. ``` (defmethod key-released ["My window name" \c] [event state] ;; do something after 'c' is released (assoc state :some (calculate-something state))) ```
Called when key is typed (pressed and released).
Should return state.
(defmethod key-typed ["My window name" \c] [event state]
;; do something when 'c' is typed
(assoc state :some (calculate-something state)))
Called when key is typed (pressed and released). * Dispatch: vector of window name and key char * Params: key event and current state. Should return state. ``` (defmethod key-typed ["My window name" \c] [event state] ;; do something when 'c' is typed (assoc state :some (calculate-something state))) ```
(line canvas vect1 vect2)
(line canvas x1 y1 x2 y2)
Draw line from point (x1,y1)
to (x2,y2)
Draw line from point `(x1,y1)` to `(x2,y2)`
(load-bytes file)
Load file and return byte array.
Load file and return byte array.
(load-image filename)
Load Image from file.
For supported formats check img-reader-formats
.
Load Image from file. * Input: Image filename with absolute or relative path (relative to your project folder) * Returns BufferedImage object or nil when Image can't be loaded. For supported formats check [[img-reader-formats]].
(load-svg svg-filename)
Load image into Batik Document. See transcode-svg
.
Load image into Batik Document. See [[transcode-svg]].
(load-url-image url)
Load image from given URL
Load image from given URL
(log message)
Log message to file or console
Log message to file or console
(log-name)
Returns log file name with path.
Returns log file name with path.
(long-array-2d sizex sizey)
Create 2d int array getter and setter methods. Array is mutable!
Create 2d int array getter and setter methods. Array is mutable!
(make-counter)
(make-counter v)
Create counter function, each call returns next number.
Create counter function, each call returns next number.
(make-graphics canvas)
Create new Graphics2D
object and set rendering hints.
Do not use directly. Call with-canvas->
or with-canvas
macros.
Create new `Graphics2D` object and set rendering hints. Do not use directly. Call [[with-canvas->]] or [[with-canvas]] macros.
(meta-down? e)
META key state as boolean.
META key state as boolean.
(mouse-button m)
Get mouse pressed button status: :left :right :center or :none
Get mouse pressed button status: :left :right :center or :none
Called on mouse event
mouse-event-map
.Should return state.
(defmethod mouse-event ["My window name" :mouse-pressed] [event state]
;; do something when button is pressed
(do-something)
state)
Called on mouse event * Dispatch: vector of window name and mouse event. See [[mouse-event-map]]. * Params: key event and current state. Should return state. ``` (defmethod mouse-event ["My window name" :mouse-pressed] [event state] ;; do something when button is pressed (do-something) state) ```
(mouse-in-window? window)
Check if mouse is inside window.
Check if mouse is inside window.
(mouse-pos m)
Mouse position as [[Vec2]] type. [0,0] - top left, [-1,-1] outside window.
Mouse position as [[Vec2]] type. [0,0] - top left, [-1,-1] outside window.
(mouse-pressed? w)
Any mouse button pressed? (boolean)
Any mouse button pressed? (boolean)
(mouse-x m)
Mouse horizontal position within window. 0 - left side. -1 outside window.
Mouse horizontal position within window. 0 - left side. -1 outside window.
(mouse-y m)
Mouse vertical position within window. 0 - left side. -1 outside window.
Mouse vertical position within window. 0 - left side. -1 outside window.
(next-filename prefix)
(next-filename prefix suffix)
Create next unique filename based on session
Create next unique filename based on session
Place origin into one of four window corners and reorient axes.
-
as suffix - means default orientation (y-axis reversed)+
as suffix - means usual (mathematical) orientation (y-axis not reversed).Place origin into one of four window corners and reorient axes. * `-` as suffix - means default orientation (y-axis reversed) * `+` as suffix - means usual (mathematical) orientation (y-axis not reversed).
(paint-mode canvas)
Set normal paint mode. This is default mode. See [[gradient-mode]] or [[xor-mode]] for other types.
(path canvas vs)
(path canvas vs close?)
(path canvas vs close? stroke?)
Draw path from lines.
Input: list of points as vectors, close? - close path or not (default: false), stroke? - draw lines or filled shape (default true - lines).
See also path-bezier
.
Draw path from lines. Input: list of points as vectors, close? - close path or not (default: false), stroke? - draw lines or filled shape (default true - lines). See also [[path-bezier]].
(path-bezier canvas vs)
(path-bezier canvas vs close?)
(path-bezier canvas vs close? stroke?)
Draw path from quad curves.
Input: list of points as vectors, close? - close path or not (default: false), stroke? - draw lines or filled shape (default true - lines).
See also path
.
Draw path from quad curves. Input: list of points as vectors, close? - close path or not (default: false), stroke? - draw lines or filled shape (default true - lines). See also [[path]].
(pattern-mode canvas image)
(pattern-mode canvas image w h)
(pattern-mode canvas image anchor-x anchor-y w h)
Set paint mode to pattern.
Default anchor is set to (0,0)
. Default width and height are the same as texture dimensions.
To revert call paint-mode
Set paint mode to pattern. Default anchor is set to `(0,0)`. Default width and height are the same as texture dimensions. To revert call [[paint-mode]]
(point canvas vect)
(point canvas x y)
Draw point at x
,y
or at vector position.
It's implemented as a very short line. Consider using (rect x y 1 1)
for speed when x
and y
are integers.
Draw point at `x`,`y` or at vector position. It's implemented as a very short line. Consider using `(rect x y 1 1)` for speed when `x` and `y` are integers.
(pointy-hex canvas x y size)
(pointy-hex canvas x y size stroke?)
Draw pointy topped hex.
Draw pointy topped hex.
(pop-matrix canvas)
Restore saved transformation state.
See also push-matrix
, reset-matrix
.
Restore saved transformation state. See also [[push-matrix]], [[reset-matrix]].
(push-matrix canvas)
Remember current transformation state.
See also pop-matrix
, reset-matrix
.
Remember current transformation state. See also [[pop-matrix]], [[reset-matrix]].
(quad canvas x1 y1 x2 y2 x3 y3 x4 y4)
(quad canvas x1 y1 x2 y2 x3 y3 x4 y4 stroke?)
Draw quad with corners at 4 positions.
Draw quad with corners at 4 positions.
(rarc canvas x1 y1 r start extent)
(rarc canvas x1 y1 r start extent type)
(rarc canvas x1 y1 r start extent type stroke?)
Draw arc with middle at (x,y)
with radius r
.
Starting angle start
and extent
are in radians. Direction is clockwise.
Type is one of the:
:open
:pie
:chord
Draw arc with middle at `(x,y)` with radius `r`. Starting angle `start` and `extent` are in radians. Direction is clockwise. Type is one of the: * `:open` * `:pie` * `:chord`
(rect canvas x y w h)
(rect canvas x y w h stroke?)
Draw rectangle with top-left corner at (x,y)
position with width w
and height h
. Optionally you can set stroke?
(default: false
) to true
if you don't want to fill rectangle and draw outline only.
See also: crect
.
Draw rectangle with top-left corner at `(x,y)` position with width `w` and height `h`. Optionally you can set `stroke?` (default: `false`) to `true` if you don't want to fill rectangle and draw outline only. See also: [[crect]].
Rendering hints define quality of drawing or window rendering.
The differences are in interpolation, antialiasing, speed vs quality rendering etc. See the source code for the list of each value.
The :highest
is :high
with VALUE_STROKE_PURE
added. Be aware that this option can give very soft lines.
Default hint for Canvas is :high
. You can set also hint for Window which means that when display is refreshed this hint is applied (java defaults are used otherwise).
Rendering hints define quality of drawing or window rendering. The differences are in interpolation, antialiasing, speed vs quality rendering etc. See the source code for the list of each value. The `:highest` is `:high` with `VALUE_STROKE_PURE` added. Be aware that this option can give very soft lines. Default hint for Canvas is `:high`. You can set also hint for Window which means that when display is refreshed this hint is applied (java defaults are used otherwise).
(replace-canvas window canvas)
Replace canvas in window.
Replace canvas in window. * Input: window and new canvas * Returns canvas
(reset-clip canvas)
Resets current clipping.
See also clip
.
Resets current clipping. See also [[clip]].
(reset-matrix canvas)
Reset transformations.
Reset transformations.
Save Image to the file.
Preprocess if necessary (depends on file type). For supported formats check img-writer-formats
.
Dispatch is based on extension as keyword, ie. ".jpg" -> :jpg
.
Save Image to the file. Preprocess if necessary (depends on file type). For supported formats check [[img-writer-formats]]. Dispatch is based on extension as keyword, ie. ".jpg" -> `:jpg`.
(save-image b filename)
Save image to the file.
BufferedImage
object) and filenameImage is saved using save-file-type
multimethod.
Save image to the file. * Input: image (`BufferedImage` object) and filename * Side effect: saved image Image is saved using [[save-file-type]] multimethod.
(screen-height)
Returns height of the screen.
Returns height of the screen.
(screen-width)
Returns width of the screen.
Returns width of the screen.
(set-awt-background canvas c)
Set background color. Expects valid java.awt.Color
object.
Set background color. Expects valid `java.awt.Color` object.
(set-awt-color canvas c)
Set color with valid java Color
object. Use it when you're sure you pass java.awt.Color
object.
Set color with valid java `Color` object. Use it when you're sure you pass `java.awt.Color` object.
Sets background with given color. Background can be set with alpha. See [[set-color]].
Sets current color. Color can be:
See clojure2d.color
namespace for more color functions.
Sets current color. Color can be: * [[vec3]], [[vec4]] with rgb values. * java.awt.Color object * keyword with name from 140 HTML color names * Integer * r, g, b and optional alpha See [[clojure2d.color]] namespace for more color functions.
(set-composite canvas)
(set-composite canvas composite)
Set composite method for blending during draw.
See [[composite]] to create one defined by clojure2d.color
blending modes.
You can also use ones defined in java.awt.AlphaComposite
class.
Call witout parameters to revert to default: java.awt.AlphaComposite/SrcOver
.
Set composite method for blending during draw. See [[composite]] to create one defined by [[clojure2d.color]] blending modes. You can also use ones defined in `java.awt.AlphaComposite` class. Call witout parameters to revert to default: `java.awt.AlphaComposite/SrcOver`.
(set-font-attributes canvas size)
(set-font-attributes canvas size style)
Set current font size and attributes.
Attributes are: :bold
, :italic
, :bold-italic
.
Set current font size and attributes. Attributes are: `:bold`, `:italic`, `:bold-italic`.
(set-state! w state)
Changle global state for Window.
Changle global state for Window.
(set-stroke canvas)
(set-stroke canvas size)
(set-stroke canvas size cap)
(set-stroke canvas size cap join)
(set-stroke canvas size cap join miter-limit)
Set stroke (line) attributes like cap
, join
, size and miter-limit
.
Default :round
and :bevel
are used. Default size and miter-limit are 1.0
.
See stroke-joins
and stroke-caps
for names.
See set-stroke-custom
.
Set stroke (line) attributes like `cap`, `join`, size and `miter-limit`. Default `:round` and `:bevel` are used. Default size and miter-limit are `1.0`. See [[stroke-joins]] and [[stroke-caps]] for names. See [[set-stroke-custom]].
(set-stroke-custom
canvas
{:keys [size cap join miter-limit dash dash-phase]
:or
{size 1.0 cap :butt join :round miter-limit 1.0 dash nil dash-phase 0.0}})
Create custom stroke.
Provide map with following entries, see more in JavaDoc:
stroke-caps
(default: :butt)stroke-joins
(default: :round)See also set-stroke
.
Create custom stroke. Provide map with following entries, see more in [JavaDoc](https://docs.oracle.com/javase/7/docs/api/java/awt/BasicStroke.html): * :size - size of the stroke (default: 1.0) * :cap - [[stroke-caps]] (default: :butt) * :join - [[stroke-joins]] (default: :round) * :miter-limit - line joins trim factor (default: 1.0) * :dash - array with dash pattern, (default: nil) * :dash-phase - offset to start pattern (default: 0.0) See also [[set-stroke]].
(shift-down? e)
SHIFT key state as boolean.
SHIFT key state as boolean.
(show-window)
(show-window {:keys [canvas window-name w h fps draw-fn state draw-state setup
hint refresher always-on-top? background]
:or {always-on-top? false
draw-state nil
draw-fn nil
background :white
window-name (str "Clojure2D - "
(to-hex (rand-int (Integer/MAX_VALUE)) 8))
state nil
hint nil
canvas (canvas 200 200)
fps 60
setup nil
refresher nil}})
(show-window canvas window-name)
(show-window canvas window-name draw-fn)
(show-window canvas window-name fps draw-fn)
(show-window canvas window-name w h fps)
(show-window canvas window-name w h fps draw-fn)
Show window for given canvas
Window
type valueAs parameters you can provide a map with folowing keys:
:canvas
- canvas attached to window (default is canvas 200x200 px):window-name
- window name, used also for events dispatch and global state:w
- width of the window (default as canvas width):h
- height of the window (default as canvas heiht):fps
- refresh rate:draw-fn
- drawing callback (fn [canvas window frame loop-state] ... new-loop-state):state
- initial global state data:draw-state
- initial drawing state:setup
- inital callback function, returns drawing state (fn [canvas window] ... initial-loop-state):hint
- rendering hint for display: :low
, :mid
, :high
or :highest
:refresher
- :safe
(default) or :fast
:background
- background color for window panel, default white.Show window for given canvas * Returns `Window` type value As parameters you can provide a map with folowing keys: * `:canvas` - canvas attached to window (default is canvas 200x200 px) * `:window-name` - window name, used also for events dispatch and global state * `:w` - width of the window (default as canvas width) * `:h` - height of the window (default as canvas heiht) * `:fps` - refresh rate * `:draw-fn` - drawing callback (fn [canvas window frame loop-state] ... new-loop-state) * `:state` - initial global state data * `:draw-state` - initial drawing state * `:setup` - inital callback function, returns drawing state (fn [canvas window] ... initial-loop-state) * `:hint` - rendering hint for display: `:low`, `:mid`, `:high` or `:highest` * `:refresher` - `:safe` (default) or `:fast` * `:background` - background color for window panel, default white.
(subimage i x y w h)
Return rectangular subimage
Return rectangular subimage
(text canvas s x y)
(text canvas s x y align)
Draw text for given position and alignment.
Possible alignments are: :right
, :center
, :left
.
Draw text for given position and alignment. Possible alignments are: `:right`, `:center`, `:left`.
(text-bounding-box canvas txt)
Returns bounding box [x,y,w,h] for given text. [x,y]
position is relative to base line.
Returns bounding box [x,y,w,h] for given text. `[x,y]` position is relative to base line.
(text-width canvas txt)
Returns width of the provided string. Should be called within context.
Returns width of the provided string. Should be called within context.
(to-hex n)
(to-hex n pad)
Return hex value of given number, padded with leading zeroes if given length
Return hex value of given number, padded with leading zeroes if given length
(transcode-svg input w h)
Convert transcoder input into BufferedImage. See load-svg
.
Convert transcoder input into BufferedImage. See [[load-svg]].
(transform canvas [x y])
(transform canvas x y)
Transform given point or coordinates with current transformation. See inv-transform
.
Transform given point or coordinates with current transformation. See [[inv-transform]].
(translate canvas [x y])
(translate canvas tx ty)
Translate origin
Translate origin
(triangle canvas x1 y1 x2 y2 x3 y3)
(triangle canvas x1 y1 x2 y2 x3 y3 stroke?)
Draw triangle with corners at 3 positions.
Draw triangle with corners at 3 positions.
(triangle-fan canvas vs)
(triangle-fan canvas vs stroke?)
Draw triangle fan. Implementation of Processing
FAN
shape.
First point is common vertex of all triangles.
Input: list of vertices as vectors.
See also: triangle-strip
.
Draw triangle fan. Implementation of `Processing` `FAN` shape. First point is common vertex of all triangles. Input: list of vertices as vectors. See also: [[triangle-strip]].
(triangle-strip canvas vs)
(triangle-strip canvas vs stroke?)
Draw triangle strip. Implementation of Processing
STRIP
shape.
Input: list of vertices as vectors.
See also: triangle-fan
.
Draw triangle strip. Implementation of `Processing` `STRIP` shape. Input: list of vertices as vectors. See also: [[triangle-fan]].
Use as a dispatch in key events for keys like up/down/etc.
Use as a dispatch in key events for keys like up/down/etc.
(window-active? window)
Helper function, check if window is active.
Helper function, check if window is active.
(with-canvas [c canvas] & body)
Macro which takes care to create and destroy Graphics2D
object for drawings on canvas. Macro returns result of last call.
See also with-canvas->
.
Macro which takes care to create and destroy `Graphics2D` object for drawings on canvas. Macro returns result of last call. See also [[with-canvas->]].
(with-canvas-> canvas & body)
Threading macro which takes care to create and destroy Graphics2D
object for drawings on canvas. Macro returns result of last call.
Each function have to accept canvas as second parameter and have to return canvas.
See also with-canvas
.
Threading macro which takes care to create and destroy `Graphics2D` object for drawings on canvas. Macro returns result of last call. Each function have to accept canvas as second parameter and have to return canvas. See also [[with-canvas]].
(with-oriented-canvas orientation [c canv] & body)
Same as with-canvas
but with initial orientation.
Same as [[with-canvas]] but with initial orientation.
(with-oriented-canvas-> orientation canv & body)
Same as with-canvas->
but with initial orientation.
Same as [[with-canvas->]] but with initial orientation.
cljdoc is a website building & hosting documentation for Clojure/Script libraries
× close