torsdag 21 mars 2013

Minimal C2 bind! example

 C2 is a very sane vizualisation library for both Clojure and ClojureScript.

I had a hard time grasping bind! and unify, so I wanted to make the smallest example I could think of: generate a blue svg circle.

From O'Reilly's excellent introduction to SVG (available online) I found that the XML for an SVG circle would be something like:

<svg width="400px" height="400px">
 <circle cx="100" cy="100" r="45" style="fill: 'blue';"/>

I did once spend unreasonably long time to try to reach the DOM of an embedded SVG image, so from now on I embed the SVG DOM root in my html document, like this document with an empty SVG tag with id "bubbles":

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="">
  <title>SVG bubble</title>

  <svg id="bubbles"></svg></div>
 <script src="/cljscode.js"></script>

C2 transforms tags like Hiccup do, but you can say where you want to add it with the macro c2.util/bind! (works a bit like in enlive).

And some very minimal ClojureScript code:

(ns c2test.core
 (:require  [c2.core :as c2core])
 (:require-macros [c2.util :as c2util]))

(defn ^:export c2bubble [x y r]
  (c2util/bind! "#bubbles"
                [:svg#bubbles {:style  {:display "block" :margin "auto" :height 200 :width 200}}
                 [:circle {:cx x :cy y :r r :style { :fill "blue"}}]]))

By opening a browser console (for javascript) I can set coordinates of a blue bubble with a command like


Now on to world domination.

Inga kommentarer:

Skicka en kommentar