Daniel Oliveira Daniel Oliveira - 2 months ago 16
CSS Question

Expand HTML5 canvas to the whole document

I am making an multiplayer game using the HTML5 canvas element.
At this moment I expand the canvas to the whole window with this javascript code:

var WIDTH = window.innerWidth;
var HEIGHT = window.innerHeight;
var canvas =document.getElementById("gameCanvas");
canvas.width = WIDTH;
canvas.height = HEIGHT;


Using the code above the canvas will occupy the whole document space and it will have WIDTH px on the xx axis and HEIGHT px on the yy axis and this is not really what I want because some players with higher resolution will have a more expansive view of the game map than members with lower resolutions.

Question: Is there anyway to expand the canvas to the whole document and keep a fixed number of "canvas pixels" on each axis independent of the user's screen resolution?

Thanks!

Answer

You can use the canvas function scale() or scale the canvas via css. This would be an example of implementing a solution with the canvas function:

var canvas = document.getElementById("gameCanvas");
var ctx = canvas.getContext("2d");
var WIDTH = window.innerWidth;
var HEIGHT = window.innerHeight;
var x = WIDTH/c.width;
var y = HEIGHT/c.height;

c.width=WIDTH;
c.height=HEIGHT;

ctx.scale(x,y);
ctx.strokeRect(5, 5, 140, 140);
Comments