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';"/>
</svg> 

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="http://www.w3.org/1999/xhtml">
 <head>
  <title>SVG bubble</title>
 </head>
 <body>
 <div>

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


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

c2test.core.c2bubble(20,50,30);

Now on to world domination.

Inga kommentarer:

Skicka en kommentar