YoshiJaeger
YoshiJaeger

Reputation: 1210

Coordinates of a scaled canvas element

I already made use of a search engine, but I did not get the information I wanted, so I want to ask whether someone has a good method/trick for using a self-made coordinate system in a HTML5 canvas element.

I want to develop a 2D game in HTML5 using the canvas element, which should adapt to the whole browser window, like so:

<canvas style="width: 100%; height: 100%;">
     No support for your browser, unfortunately...
</canvas>

The problem is that I do not know how I should manage the coordinates of my game. In my game the player e.g. moves 32px to the right immediately when the user presses the right arrow key, but what happens, if I resize the canvas element? Logically the "blocks" of the game will change their size too, so the unit of the coordinates will not be pixels anymore.

Are there other units I could use or what would you suggest me to do?

Upvotes: 2

Views: 5854

Answers (2)

Simon Sarris
Simon Sarris

Reputation: 63802

Never ever ever use CSS sizing for the canvas, they will make things very ugly.

What you wrote does not make your canvas the width of the page, it makes it 300 pixels wide by 150 pixels tall (the default) and then warps that until its the width and height of the page.

Stick to the width and height attributes that Canvas has instead of using CSS.

If you want to make it the size of the page you have other options, such as putting the canvas inside a div and then making canvas.width equal to the div.style.clientWidth.

For working with different (fullscreen or not) window sizes, see my answer talking about "model coordinates" here: Working with canvas in different screen sizes

Upvotes: 0

Teemu Ikonen
Teemu Ikonen

Reputation: 11929

Set canvas width and height attributes to game area size

<canvas id="mycanvas" width="400" height="300"/>

And set its style to the desired display size on screen.

#mycanvas {
    width: 100%
    height: 100%
    display: block
}

Now you can always assume in the code that canvas is 400x300 and when drawing ignore the actual physical pixel size on screen.

You need to scale the mouse clicks to correspond the actual location on game coordinates. So if you get mouse click on canvas at (x, y) you get location on game coordinates by x = ( x / $('#mycanvas').width()) * 400 and y likewise. If canvas is not full screen, use the $('#mycanvas').offset() to get delta for click coordinates.

Upvotes: 6

Related Questions