Canvas distorts drawing. How do I get the scale factor between the set size and the styled size?

StackOverflow https://stackoverflow.com/questions/7545863

  •  29-01-2021
  •  | 
  •  

Question

I have this canvas:

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

The css styles the canvas via:

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

As the width can change, the canvas distorts the drawing. I need to know how to compensate for this. Anyone who can help me?

Was it helpful?

Solution

This is the same problem that the Mozilla Bespin team ran into. (back when they were using Canvas, before it merged with Ace)

Don't give the Canvas any CSS width/height rules. Doing so usually ends up as a pain. Put the Canvas in a Div that only has a single thing in it (the canvas itself)

As the canvas-parent div changes size, change the size of the canvas (canvas.width and canvas.height) to match the size of the div.

Since most browsers do not fire an event when a div changes size, you'll simply have to check, say, every half second with a timer to see if the div has changed size. If it has, then you resize the canvas accordingly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top