HTML5 canvas style height vs attribute height
Asked Answered
E

2

0

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

Ervin answered 22/11, 2012 at 5:21 Comment(0)
M
2

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.

Moonlit answered 22/11, 2012 at 5:39 Comment(0)
J
0
  • 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.

Jidda answered 13/6, 2022 at 12:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.