Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 801
Kriem Avatar asked Sep 25 '11 13:09

Kriem


People also ask

How do you scale a canvas size?

With the Select and Move Tool, click the canvas size label or border to select the canvas. Click the canvas border handles to resize the canvas dynamically. When you drag the border handles without using any keyboard modifiers, the canvas resizes non-uniformly. Hold Shift to constrain the resize proportions.

What is scale () in canvas?

The scale() method scales the current drawing, bigger or smaller. Note: If you scale a drawing, all future drawings will also be scaled. The positioning will also be scaled. If you scale(2,2); drawings will be positioned twice as far from the left and top of the canvas as you specify.

How do I change a ratio in canvas?

"Change Canvas Size" command in Canvas tool lets you change the size of the canvas. Open ① the Tool Selection windowand select ② Canvas tool. Select ① Change Canvas Size. ① Keep Aspect Ratio, which will keep the given ratio between the width and the height of the canvas.

How do I change the width and height of a dynamic canvas?

To do it, simply set the width and height properties of the Canvas object, and then redraw the canvas contents: Canvas . width = 600 ; Canvas . height = 500 ; drawScreen ();


1 Answers

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.

like image 172
Simon Sarris Avatar answered Sep 23 '22 23:09

Simon Sarris