The canvas distorts the picture. How to get a scale factor between the set size and the size of the styles?

I have this canvas:

<canvas id="game" width="280" height="280"></canvas> 

css styles the canvas with:

 canvas { width: inherit; height: 280px; } 

As the width changes, the canvas distorts the picture. I need to know how to compensate for this. Who can help me?

+6
source share
1 answer

This is the same problem that the Mozilla Bespin team faced. (back when they used Canvas before it merged with Ace)

Do not give Canvas any CSS width and height rules. Doing this usually ends up like pain. Put the canvas in a div that has only one thing (the canvas itself)

As the canvas-parent file size changes, resize the canvas (canvas.width and canvas.height) to fit the size of the div.

Since most browsers do not fire an event when a div resizes, you just need to check, say, every half second with a timer to see if the div has resized. If it does, then you resize the canvas accordingly.

+9
source

Source: https://habr.com/ru/post/898011/


All Articles