Can Can不能在Canvas上绘制图像()

时间:2014-05-19 22:01:15

标签: html5 canvas clojurescript

我似乎无法呈现subsection of a PNG to an HTML canvas。我有一个画布2D上下文和一个预加载的图像,onload我尝试在画布上绘制图像,但没有任何反应。我的浏览器控制台也没有错误。

(ns jump.core)

(enable-console-print!)

(defn screen
  ([]
     (screen "screen"))
  ([elem-id]
     (let [screen (.getElementById js/document elem-id)]
       {:context (.getContext screen "2d")
        :height (.-height screen)
        :width (.-width screen)})))

(defn draw-sprite
  [player screen]
  (let [ctx (:context screen)
        sprite (:image player)
        t (:top player)
        l (:left player)
        w (:width player)
        h (:height player)]
    (println ctx sprite l t w h 10 10 w h)
    (.drawImage ctx sprite l t w h 10 10 w h)))

(defn image
  [src]
  (let [img (new js/Image)]
    (set! (.-src img) src)
    img))

(def player
  {:image (image "sprites/player.png")
   :top 94
   :left 167
   :height 35
   :width 37
   :facing :right
   :falling false
   :jumping false})

(set! (.-onload js/window)
      (do
        (println "Window loaded")
        (println "player" player)
        (println "screen" (screen))
        (draw-sprite player (screen))))

完整代码可在my github repo中找到。

browser console output

2 个答案:

答案 0 :(得分:0)

你可能要等到onload在图像中闪现,当你画它时它可能是空的,因为它仍然没有从服务器回来。

快速而丑陋的解决方案:

(defn init []
  (println "Window loaded")
  (println "player" player)
  (println "screen" (screen))
  (draw-sprite player (screen)))

(set! (.-onload js/window)
      #(set! (.-onload (:image player))
             init))

如果这是问题,您可能需要一些代码来管理加载资源!

-

另外,我注意到你要分配给window.onload do表达式的结果。您可能想要分配一个匿名函数:

(set! (.-onload js/window)
      #(do
        (println "Window loaded")
        (println "player" player)
        (println "screen" (screen))
        (draw-sprite player (screen))))

答案 1 :(得分:0)

对于找到这个问题的未来人,这是我的解决方案。我选择使用Base64图像编码,以便在画布尝试绘制图像时立即加载图像。

  1. 首先,我获取将绘制图像的画布:

    (defn canvas
      "gets a canvas with a certain id"
      [id]
      (.getElementById js/document id))
    
  2. 然后我检索该画布的上下文。

    (defn context-2d
      "gets the 2d context of a canvas with an id"
      [id]
      (let [canvas-elem (canvas id)]
        (.getContext canvas-elem "2d"))) 
    
  3. 接下来,我得到了合适的图片。 data对应于Base64图片编码字符串。

    ((defn get-img
      "retrieves an image with data"
      [data]
      (let [img (js/Image.)]
        (set! (.-src img) data)
        img))
    
  4. 最后,我将上一步中的图像绘制到上下文中。

    (defn draw-image
      "draws the image"
      [ctx img x y width height]
      (.drawImage ctx img x y width height))