Drawing an image onto a threepenny-gui Canvas

263 Views Asked by At

I'm having an issue with canvases. I have modified the Canvas.hs example program to draw an image onto the canvas with

canvas # drawImg

right after the canvas setup code; here it is for reference:

canvas <- UI.canvas
      # set UI.height canvasSize
      # set UI.width  canvasSize
      # set style [("border", "solid black 1px"), ("background", "#eee")]

where drawImg is

drawImg :: UI.Canvas -> UI ()
drawImg canvas = do
  url <- UI.loadFile "image/png" "resources/img.png"
  img <- UI.img # set UI.src url
  UI.drawImage img (0,0) canvas

which should be the same behavior as the on click function for drawing an image in the original version of the code.

The actual behavior of this code is a blank canvas, just as in the original example before clicking on the draw image button. I would think that it should draw the image on loading. Why is this? Should I instead add this call to the line that sets up the canvas?

1

There are 1 best solutions below

0
On

Is the canvas part of the DOM? Don't forget to add it to the document body with via getBody #+ [...] or thelike.

There may be another problem, though: Browsers usually load image URLs asynchronously. In fact, I'm not sure if they load image URLs at all if the image is not part of the DOM, as in your example. In both scenarios, if you try to draw an image to a canvas before its URL has been loaded, nothing will be drawn. (The easiest way to check whether this problem is the relevant one in your code is to draw polygons instead of an image.)