HTML5 Canvas fit parent div

The following code creates an 800x600 pixels div containing an 300x150 pixels (default size) canvas:

div [ style "width" "800px"
      , style "height" "600px" 
      , Html.Attributes.id ("item-" ++ String.fromInt 1) ]  
      [  
          canvas [ ] [ ] 
      ]  
]

There are two ways to resize the canvas:

  1. By using width and height properties.
  2. By using style "width" "..." and style "height" "...".

If I choose the 1rst method and change the canvas size to, for example, 400x500, the contained image (or drawing) isn’t stretched.

canvas [
   width 500
   , height 400
] [ ]

(I cannot post this picture, because new users can only post 1 embedded media per post…)

When I use the 2nd method the canvas is stretched. The following image is an example of an 500x300 pixels image, drawn into a 500x400 canvas, which in turn is inside an 800x600 div. As you can see the image is stretched.

canvas [
   style "width" "500px"
   , style "height" "400px"
] [ ]

Knowing this, I would like to know the size of the parent div and assign the same width and height to the canvas, how can I do that?.

I think you can do that in two ways:

You might want to keep track of window resize too (and potentially resize of the canvas parent) so you have to install a subscription for the resize event too in your Elm app.

Thanks, I opted for creating one port and subscribing to it. The port is triggered by the resize event of the window.

I also created a 2nd port that is called at init to ask for the dimensions.

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.