Munsta0
Munsta0

Reputation: 121

HTML5 canvas style height vs attribute height

I am currently learning how to use HTML5 new elements and I stumbled upon a frustrating issue with all graphic functions such as fillRect() and drawImage().

I was setting the widgth and height with

style="width: 75px;height: 10px;"

instead of

width="200" height="100"

The result being that the graphics would not be the proper scale ever.

My question is, why does it make a difference? There is something I obviously do not understand about it all.

Thank you

Upvotes: 0

Views: 951

Answers (2)

K P
K P

Reputation: 41

  • It was an extremely frustrating issue trying to figure out why canvas doesn't render its shapes correctly despite doing everything right.
  • The fix was to set "canvas.height" and "canvas.width" correctly. Just setting "canvas.style.height" and "canvas.style.width" doesn't rectify internal rendering of the canvas.
  • Almost every time, your

canvas.height = canvas.style.height

AND

canvas.width = canvas.style.width

I read somewhere that the HTML engine refers "canvas.width" and "canvas.height" while doing the calculations for painting shapes and text inside the canvas.

Whereas, "canvas.style.height" and "canvas.style.width" only determine how the browser displays that canvas alongside other HTML DOM elements. Thanks to bjedrzejewski and Munsta0 for asking this question.

Upvotes: 0

bjedrzejewski
bjedrzejewski

Reputation: 2436

I know that at least in JSF (specifically primefaces) the difference is that if you put height in the style- it will not be used to properly calculate and render the component (the more complex ones) sometimes. If you put it as attribute then it will work.

If HTML5 takes the similar approach it would mean that attribute height and width are the actual height and width of the component and the style is just the way to display it. Sometimes however, both approaches are going to end with the same result.

Also in primefaces when you specify height and width as attribute- you can not use percentages. This could be the key- an additional measure of enforcing specific width and heights rathen than percentages.

Upvotes: 2

Related Questions