4

在 Clojurescript 中将 SVG 元素添加到 dom 的最佳方法是什么?(dom/build [:svg [:g [:text "something like this ?"]]]) Twitterbuzz示例使用 Google Closure lib 的 Graphics 对象,但说我不关心 IE 兼容性,有没有办法可以像 html 一样添加元素SVG 功能。我试过 Apogee,但它会序列化 SVG 代码,我更喜欢直接 DOM 操作。

4

4 回答 4

4

dom/build 构造没有命名空间的 DOM 元素。您需要增强 dom/build 或为 SVG 编写一个。我使用以下代码创建 SVG 元素。

(defn element-ns
  "Create a namespaced dom element"
  [namespace tag & args]
  (let [[tag attrs children] (normalize-args tag args)
        parent (. js/document createElementNS namespace (name tag))
        [parent children] (if (string? (first children))
                            [(set-text (element-ns namespace tag attrs) (first children))
                             (rest children)]
                            [parent children])]
    (doseq [[k v] attrs]
      (. parent setAttributeNS nil (name k) v))
    (apply append parent children)))

(defn build-svg
  "Build up a svg element from nested vectors."
  [x]
  (if (vector? x)
    (let [[parent children] (if (keyword? (first x))
                          [(apply element-ns "http://www.w3.org/2000/svg" (take-while element-arg? x))
                           (drop-while element-arg? x)]
                          [(first x) (rest x)])
       children (map build-svg children)]
       (apply append parent children))
    x))
于 2011-10-08T05:08:01.373 回答
3

您可能对我的cljs-d3库感兴趣,它是 D3 JavaScript 库的 ClojureScript 包装器。D3 是操作 SVG DOM 的出色工具。

于 2011-10-24T04:11:52.957 回答
2

为 SVG使用Enlive怎么样?这是我计划在几个实时项目中使用的。

于 2012-02-05T18:52:09.803 回答
0

如果您想将 svg 作为外部资源加载,请尝试将其加载为文本并利用 cljs-d3 将其附加到 div:

(defn load-svg-as-text []
 (fn []
   (let [on-complete (fn [error externalSVGText]
    (-> d3
     (.select "#viewport")
     (.html externalSVGText))
    )]
  (-> d3
    (.text "images/smartcity.svg" on-complete)))))

我从AmeliaBR在这个js 线程中得到了很好的答案,然后将其移植到 ClojureScript

于 2018-09-26T04:07:34.847 回答