468

How can I automatically scale the HTML5 <canvas> element to fit the page?

For example, I can get a <div> to scale by setting the height and width properties to 100%, but a <canvas> won't scale, will it?

gman
  • 100,619
  • 31
  • 269
  • 393
devyn
  • 16,615
  • 6
  • 24
  • 14
  • 8
    why canvas{width:100%;height:100%} don't work? – zloctb Dec 16 '14 at 17:59
  • 44
    @zloctb - That will scale up the canvas directly, which stretches your image. – Derek 朕會功夫 Jan 02 '15 at 20:26
  • 13
    See the [WebGL Fundamentals](http://webglfundamentals.org/webgl/lessons/webgl-anti-patterns.html) for a detailed explanation on what and what not to do for related issues. – legends2k Jul 19 '16 at 14:17
  • 2
    A canvas will also scale fine, just add the css {width:100%}, its contents won't however, that is another matter entirely! – ejectamenta Nov 29 '16 at 18:15
  • @legends2k The WebGL fundamentals you linked were written by [@gman](https://stackoverflow.com/users/128511/gman). Check out [his answer](https://stackoverflow.com/a/73831830/4510033) on this page. – Константин Ван Nov 28 '22 at 17:01

18 Answers18

420

I believe I have found an elegant solution to this:

JavaScript

/* important! for alignment, you should make things
 * relative to the canvas' current width/height.
 */
function draw() {
  var ctx = (a canvas context);
  ctx.canvas.width  = window.innerWidth;
  ctx.canvas.height = window.innerHeight;
  //...drawing code...
}

CSS

html, body {
  width:  100%;
  height: 100%;
  margin: 0;
}

Hasn't had any large negative performance impact for me, so far.

vallentin
  • 23,478
  • 6
  • 59
  • 81
devyn
  • 16,615
  • 6
  • 24
  • 14
  • You can set this on a separate interval if you wish too. – devyn Aug 13 '10 at 04:46
  • I have tried this and I'm consistently getting scrollbars. I checked the width of my html file element (in the console, looking at computed style) and it's always a few pixels less than what window.innerWidth is returning. Any ideas? – Elisabeth Jul 17 '11 at 20:35
  • 7
    You probably have to disable margin with `body, html { margin: 0px;}` – Nicklas A. Sep 11 '11 at 03:43
  • 49
    Is this preferable to listening to the resize event? – Eric Sep 28 '11 at 07:15
  • ctx.canvas.width = window.innerWidth; Firebug says here "annonymous function. Why? – 最白目 Nov 07 '11 at 10:59
  • 2
    @dan: some FF add-ons can botch the innerWidth property. – jerseyboy Jan 25 '12 at 14:37
  • 32
    @Elisabeth: To get rid of the scrollbars, add "overflow: hidden" to the style of the html and body elements. See http://www.thefutureoftheweb.com/blog/100-percent-height-interface – Denis Washington Mar 16 '12 at 07:45
  • 21
    I did this plus I also set canvas to display: block (it seemed to be defaulting to display: inline which was creating extra space!). – Elisabeth Apr 05 '12 at 22:00
  • 1
    @Eric, I found that setting the canvas width will clear the canvas. See mcrider's answer here: http://stackoverflow.com/a/5517885/101923 For many games that redraw the whole screen, anyway this is not a problem, but it was for me. – Tim Swast Aug 11 '13 at 03:03
  • I'm suspicious of this answer... doesn't setting width/height also discard your canvas context's transforms? Doesn't it reset all canvas state (e.g. transformations, lineWidth, strokeStyle, etc.)? – Ziggy Feb 04 '15 at 23:01
  • 3
    Using this on firefox mobile had a great performance impact on my web application, the fps dropped at an unbearable level, and it made the browser crash eventually. Doing the resize on the "onresize" event instead of this made the application work again with no aparent difference. Apart from that, It just feels wrong to resize on each drawcall when there's really no need to do so. – Setzer22 Aug 16 '15 at 15:43
  • 2
    FYI: If you already have a handle to the canvas via using the DOM, you do not need to reference via the context. I.E. `getElementById("MyCanvas") == ctx.canvas` – Nicholas Miller Aug 21 '15 at 04:16
  • 18
    This may be an anti-pattern; see [the third item here](http://webglfundamentals.org/webgl/lessons/webgl-anti-patterns.html) for the reason and remedy. – legends2k Jul 19 '16 at 14:10
  • 2
    But you need to scale the canvas objects to fit the new size – David Torroija Sep 23 '16 at 14:36
  • 3
    Sure would be nice if somebody could explain *why* this works. – l33t Oct 10 '16 at 16:11
  • 1
    this led me to my solution. just resize to a higher resolution and re-scale to fit with css – Gibs LeFleur Nov 17 '19 at 11:26
  • @l33t I have written a long-winded explanation of how canvas sizing works: https://medium.com/@doomgoober/resizing-canvas-vector-graphics-without-aliasing-7a1f9e684e4d. Also, my answer has a complete Code Snippet you can run to see this answer fully in action: https://stackoverflow.com/a/63642064/670530 – DoomGoober Aug 29 '20 at 00:12
74

The following solution worked for me the best. Since I'm relatively new to coding, I like to have visual confirmation that something is working the way I expect it to. I found it at the following site: http://htmlcheats.com/html/resize-the-html5-canvas-dyamically/

Here's the code:

(function() {
  var
    // Obtain a reference to the canvas element using its id.
    htmlCanvas = document.getElementById('c'),
    // Obtain a graphics context on the canvas element for drawing.
    context = htmlCanvas.getContext('2d');

  // Start listening to resize events and draw canvas.
  initialize();

  function initialize() {
    // Register an event listener to call the resizeCanvas() function 
    // each time the window is resized.
    window.addEventListener('resize', resizeCanvas, false);
    // Draw canvas border for the first time.
    resizeCanvas();
  }

  // Display custom canvas. In this case it's a blue, 5 pixel 
  // border that resizes along with the browser window.
  function redraw() {
    context.strokeStyle = 'blue';
    context.lineWidth = '5';
    context.strokeRect(0, 0, window.innerWidth, window.innerHeight);
  }

  // Runs each time the DOM window resize event fires.
  // Resets the canvas dimensions to match window,
  // then draws the new borders accordingly.
  function resizeCanvas() {
    htmlCanvas.width = window.innerWidth;
    htmlCanvas.height = window.innerHeight;
    redraw();
  }
})();
html,
body {
  width: 100%;
  height: 100%;
  margin: 0px;
  border: 0;
  overflow: hidden;
  /*  Disable scrollbars */
  display: block;
  /* No floating content on sides */
}
<canvas id='c' style='position:absolute; left:0px; top:0px;'></canvas>

The blue border shows you the edge of the resizing canvas, and is always along the edge of the window, visible on all 4 sides, which was NOT the case for some of the other above answers. Hope it helps.

Alexandre B.
  • 5,387
  • 2
  • 17
  • 40
Craig Morrison
  • 757
  • 5
  • 2
  • This answer solved my problem. The `overflow: hidden` and `display: block` is what was missing for me to get this working properly. – Erunehtar Apr 06 '18 at 20:27
  • 4
    The link is broken – Nic Scozzaro Dec 02 '19 at 14:46
  • This does not work. It stretches the canvas contents. – Xan-Kun Clark-Davis Jul 10 '20 at 14:02
  • @Xan-KunClark-Davis that probably depends on you other code being dependent on the canvas width and height. – JHBonarius Jul 15 '20 at 08:50
  • It turned out to be the font scaling in windows. If was set to 125% and somehow (?) this influences the rendering of a canvas in chrome. When i set it to 100%, everything works as espected. – Xan-Kun Clark-Davis Jul 15 '20 at 11:39
  • 2
    @Xan-KunClark-Davis 125% is often related to Device Pixel Resolution adjustment. Basically, if you are on a high pixel density device, the font will appear smaller than it should... so it will scale up to make the font be normal sized. As far as I understand it. You can check the display using: window.devicePixelRatio. A normal device is 1, high DPR will often be 1.25. – DoomGoober Aug 23 '20 at 04:32
  • 1
    @DoomGoober Confirmed! window.devicePixelRatio is 1.5625 on the device in question. – Xan-Kun Clark-Davis Aug 23 '20 at 10:56
21

Basically what you have to do is to bind the onresize event to your body, once you catch the event you just need to resize the canvas using window.innerWidth and window.innerHeight.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Canvas Resize</title>

    <script type="text/javascript">
        function resize_canvas(){
            canvas = document.getElementById("canvas");
            if (canvas.width  < window.innerWidth)
            {
                canvas.width  = window.innerWidth;
            }

            if (canvas.height < window.innerHeight)
            {
                canvas.height = window.innerHeight;
            }
        }
    </script>
</head>

<body onresize="resize_canvas()">
        <canvas id="canvas">Your browser doesn't support canvas</canvas>
</body>
</html>
equiman
  • 7,810
  • 2
  • 45
  • 47
  • 1
    You could just use an event listener. – David Corbin Feb 28 '14 at 21:47
  • This has margins and shows scrollbars, plus you have to resize the screen before it does anything. – ArtOfWarfare May 28 '16 at 18:16
  • What if the canvas is larger than the viewport (when making the viewport narrower or shorter)? This solution does not seem to handle that. – Lars Gyrup Brink Nielsen Jun 06 '16 at 05:31
  • @ArtOfWarfare original questions don't mention anything about styles. But you can stylize it with css and remove margins and hide scroll bars if you like. And you simply can add ` ` then when page load then resize canvas. – equiman Jun 06 '16 at 05:56
  • @LayZee original question saya bout scale the canvas to fit the **page**, not a viewport. That's can be another question. – equiman Jun 06 '16 at 06:03
  • no it cant that would be flagged as a duplicate in 0.1 seconds on here lol – AGrush Oct 28 '20 at 07:11
19

2022 answer

The recommended way in 2022 to check if an element resized is to use ResizeObserver

const observer = new ResizeObserver(myResizeTheCanvasFn);
observer.observe(someCanvasElement);

It's better than window.addEventListener('resize', myResizeTheCanvasFn) or onresize = myResizeTheCanvasFn because it handles EVERY case of the canvas resizing, even when it's not related to the window resizing.

Similarly it makes no sense to use window.innerWidth, window.innerHeight. You want the size of the canvas itself, not the size of the window. That way, no matter where you put the canvas you'll get the correct size for the situation and won't have to re-write your sizing code.

As for getting the canvas to fill the window

html, body {
  height: 100%;
}
canvas {
  width: 100%;
  height: 100%;
  display: block;   /* this is IMPORTANT! */
}

The reason you need display: block is because by default the canvas is inline which means it includes extra space at the end. Without display: block you'll get a scrollbar. Many people fix the scrollbar issue by adding overflow: hidden to the body of the document but that's just hiding the fact that the canvas's CSS was not set correctly. It's better to fix the bug (set the canvas to display: block than to hide the bug with overflow: hidden

Full example

const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');

const observer = new ResizeObserver((entries) => {
  canvas.width = canvas.clientWidth;
  canvas.height = canvas.clientHeight;
});
observer.observe(canvas)

// not import but draw something just to showcase

const hsla = (h, s, l, a) => `hsla(${h * 360}, ${s * 100}%, ${l * 100}%, ${a})`;

function render(time) {
  const {width, height} = canvas;

  ctx.clearRect(0, 0, width, height);
  ctx.save();
  ctx.translate(width / 2, height / 2);
  ctx.rotate(time * 0.0001);
  
  const range = Math.max(width, height) * 0.8;
  const size = 64 + Math.sin(time * 0.001) * 50;
  for (let i = 0; i < range; i += size) {
    ctx.fillStyle = hsla(i / range * 0.3 + time * 0.0001, 1, 0.5, 1);
    ctx.fillRect( i, -range, size, range * 2);
    ctx.fillRect(-i, -range, size, range * 2);
  }
  
  ctx.restore();

  requestAnimationFrame(render)
}
requestAnimationFrame(render)
html, body {
  height: 100%;
  margin: 0;
}
canvas {
  width: 100%;
  height: 100%;
  display: block;
}
<canvas></canvas>

Note: there are other issues related to resizing the canvas. Specifically if you want to deal with different devicePixelRatio settings. See this article for more.

gman
  • 100,619
  • 31
  • 269
  • 393
  • Never heard if this, but it works fine. Glad there is a more modern way to do this. – Omiod Sep 27 '22 at 09:12
  • As [the article in this answer](https://webglfundamentals.org/webgl/lessons/webgl-resizing-the-canvas.html) describes, using `canvas.clientWidth`/`canvas.clientHeight` solely doesn’t precisely reflect the actual numbers of device pixels (and the actual width/height ratio from them) that the `` element is taking up, so there might be minuscule visual distortion in the pixel aspect ratio of the canvas image. – Константин Ван Nov 28 '22 at 22:00
  • 1
    For non-distorted high-density pixel-perfect canvas resizing, use [`ResizeObserverEntry.devicePixelContentBoxSize`](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserverEntry/devicePixelContentBoxSize) with CSS `width/height: 100%;`, as [@gman’s](https://webglfundamentals.org/webgl/lessons/webgl-resizing-the-canvas.html) and [Surma’s](https://web.dev/device-pixel-content-box) articles suggest. – Константин Ван Nov 28 '22 at 22:36
  • OMG, thanks for the side note for devicePixelRatio!!! I was wondering why mousemove event and canvas.isPointInPath has been behaving differently across display devices, and it took me the whole day to bump into this reply and it saved my day! Thanks! – Chan Yung Keat Apr 19 '23 at 08:20
19

Setting the canvas coordinate space width and height based on the browser client's dimensions requires you to resize and redraw whenever the browser is resized.

A less convoluted solution is to maintain the drawable dimensions in Javascript variables, but set the canvas dimensions based on the screen.width, screen.height dimensions. Use CSS to fit:

#containingDiv { 
  overflow: hidden;
}
#myCanvas {
  position: absolute; 
  top: 0px;
  left: 0px;
} 

The browser window generally won't ever be larger than the screen itself (except where the screen resolution is misreported, as it could be with non-matching dual monitors), so the background won't show and pixel proportions won't vary. The canvas pixels will be directly proportional to the screen resolution unless you use CSS to scale the canvas.

jerseyboy
  • 1,298
  • 13
  • 13
  • 8
    Rescaling canvas with CSS is troublesome. At least on Chrome and Safari, mouse/touch event positions will not correspond 1:1 with canvas pixel positions, and you'll have to transform the coordinate systems. – jerseyboy Dec 01 '11 at 15:44
17

A pure CSS approach adding to solution of @jerseyboy above.
Works in Firefox (tested in v29), Chrome (tested in v34) and Internet Explorer (tested in v11).

<!DOCTYPE html>
<html>
    <head>
    <style>
        html,
        body {
            width: 100%;
            height: 100%;
            margin: 0;
        }
        canvas {
            background-color: #ccc;
            display: block;
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            width: 100%;
            height: 100%;
        }
    </style>
</head>
<body>
    <canvas id="canvas" width="500" height="500"></canvas>
    <script>
        var canvas = document.getElementById('canvas');
        if (canvas.getContext) {
            var ctx = canvas.getContext('2d');
            ctx.fillRect(25,25,100,100);
            ctx.clearRect(45,45,60,60);
            ctx.strokeRect(50,50,50,50);
        }
    </script>
</body>
</html>

Link to the example: http://temporaer.net/open/so/140502_canvas-fit-to-window.html

But take care, as @jerseyboy states in his comment:

Rescaling canvas with CSS is troublesome. At least on Chrome and Safari, mouse/touch event positions will not correspond 1:1 with canvas pixel positions, and you'll have to transform the coordinate systems.

Volker E.
  • 5,911
  • 11
  • 47
  • 64
  • 6
    CSS way stretches the canvas, thus rendered images get stretched. This is not good compared to resizing the canvas. With little adjustment, Craig's answer works best. – Nayan Apr 06 '15 at 04:21
  • 1
    I like this solution as this makes canvas 100% based on parent width. – Maihan Nijat Mar 21 '19 at 14:42
14
function resize() {

    var canvas = document.getElementById('game');
    var canvasRatio = canvas.height / canvas.width;
    var windowRatio = window.innerHeight / window.innerWidth;
    var width;
    var height;

    if (windowRatio < canvasRatio) {
        height = window.innerHeight;
        width = height / canvasRatio;
    } else {
        width = window.innerWidth;
        height = width * canvasRatio;
    }

    canvas.style.width = width + 'px';
    canvas.style.height = height + 'px';
};

window.addEventListener('resize', resize, false);
Petr
  • 1,389
  • 10
  • 15
11

Set initial size.

const canvas = document.getElementById('canvas');

canvas.width  = window.innerWidth;
canvas.height = window.innerHeight;

Update size on window resize.

function windowResize() {
  canvas.width  = window.innerWidth;
  canvas.height = window.innerHeight;
};

window.addEventListener('resize', windowResize);
Alex V
  • 18,176
  • 5
  • 36
  • 35
8

Unless you want the canvas to upscale your image data automatically (that's what James Black's answer talks about, but it won't look pretty), you have to resize it yourself and redraw the image. Centering a canvas

Community
  • 1
  • 1
Nickolay
  • 31,095
  • 13
  • 107
  • 185
4

If your div completely filled the webpage then you can fill up that div and so have a canvas that fills up the div.

You may find this interesting, as you may need to use a css to use percentage, but, it depends on which browser you are using, and how much it is in agreement with the spec: http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#the-canvas-element

The intrinsic dimensions of the canvas element equal the size of the coordinate space, with the numbers interpreted in CSS pixels. However, the element can be sized arbitrarily by a style sheet. During rendering, the image is scaled to fit this layout size.

You may need to get the offsetWidth and height of the div, or get the window height/width and set that as the pixel value.

James Black
  • 41,583
  • 10
  • 86
  • 166
3

CSS

body { margin: 0; } 
canvas { display: block; } 

JavaScript

window.addEventListener("load", function()
{
    var canvas = document.createElement('canvas'); document.body.appendChild(canvas);
    var context = canvas.getContext('2d');

    function draw()
    {
        context.clearRect(0, 0, canvas.width, canvas.height);
        context.beginPath();
        context.moveTo(0, 0); context.lineTo(canvas.width, canvas.height); 
        context.moveTo(canvas.width, 0); context.lineTo(0, canvas.height); 
        context.stroke();
    }
    function resize()
    {
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        draw();
    }
    window.addEventListener("resize", resize);
    resize();
});
Martin Wantke
  • 4,287
  • 33
  • 21
3

If you're interested in preserving aspect ratios and doing so in pure CSS (given the aspect ratio) you can do something like below. The key is the padding-bottom on the ::content element that sizes the container element. This is sized relative to its parent's width, which is 100% by default. The ratio specified here has to match up with the ratio of the sizes on the canvas element.

// Javascript

var canvas = document.querySelector('canvas'),
    context = canvas.getContext('2d');

context.fillStyle = '#ff0000';
context.fillRect(500, 200, 200, 200);

context.fillStyle = '#000000';
context.font = '30px serif';
context.fillText('This is some text that should not be distorted, just scaled', 10, 40);
/*CSS*/

.container {
  position: relative; 
  background-color: green;
}

.container::after {
  content: ' ';
  display: block;
  padding: 0 0 50%;
}

.wrapper {
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
}

canvas {
  width: 100%;
  height: 100%;
}
<!-- HTML -->

<div class=container>
  <div class=wrapper>
    <canvas width=1200 height=600></canvas>  
  </div>
</div>
Flip
  • 6,233
  • 7
  • 46
  • 75
mrmcgreg
  • 2,754
  • 1
  • 23
  • 26
1

Using jQuery you can track the window resize and change the width of your canvas using jQuery as well.

Something like that

$( window ).resize(function() {
   $("#myCanvas").width($( window ).width())
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">
Rafael Andrade
  • 495
  • 1
  • 5
  • 22
1

Here's a tiny, complete Code Snippet that combines all the answers. Press: "Run Code Snippet" then press "Full Page" and resize the window to see it in action:

function refresh(referenceWidth, referenceHeight, drawFunction) {
  const myCanvas = document.getElementById("myCanvas");
  myCanvas.width = myCanvas.clientWidth;
  myCanvas.height = myCanvas.clientHeight;

  const ratio = Math.min(
    myCanvas.width / referenceWidth,
    myCanvas.height / referenceHeight
  );
  const ctx = myCanvas.getContext("2d");
  ctx.scale(ratio, ratio);

  drawFunction(ctx, ratio);
  window.requestAnimationFrame(() => {
    refresh(referenceWidth, referenceHeight, drawFunction);
  });
}

//100, 100 is the "reference" size. Choose whatever you want.
refresh(100, 100, (ctx, ratio) => {
  //Custom drawing code! Draw whatever you want here.
  const referenceLineWidth = 1;
  ctx.lineWidth = referenceLineWidth / ratio;
  ctx.beginPath();
  ctx.strokeStyle = "blue";
  ctx.arc(50, 50, 49, 0, 2 * Math.PI);
  ctx.stroke();
});
div {
  width: 90vw;
  height: 90vh;
}

canvas {
  width: 100%;
  height: 100%;
  object-fit: contain;
}
<div>
  <canvas id="myCanvas"></canvas>
</div>

This snippet uses canvas.clientWidth and canvas.clientHeight rather than window.innerWidth and window.innerHeight to make the snippet run inside a complex layout correctly. However, it works for full window too if you just put it in a div that uses full window. It's more flexible this way.

The snippet uses the newish window.requestAnimationFrame to repeatedly resize the canvas every frame. If you can't use this, use setTimeout instead. Also, this is inefficient. To make it more efficient, store the clientWidth and clientHeight and only recalculate and redraw when clientWidth and clientHeight change.

The idea of a "reference" resolution lets you write all of your draw commands using one resolution... and it will automatically adjust to the client size without you having to change the drawing code.

The snippet is self explanatory, but if you prefer it explained in English: https://medium.com/@doomgoober/resizing-canvas-vector-graphics-without-aliasing-7a1f9e684e4d

DoomGoober
  • 1,533
  • 14
  • 20
1

A bare minimum setup

HTML

<canvas></canvas>

CSS

html,
body {
  height: 100%;
  margin: 0;
}

canvas {
  width: 100%;
  height: 100%;
  display: block;
}

JavaScript

const canvas = document.querySelector('canvas');

const resizeObserver = new ResizeObserver(() => {
  canvas.width = Math.round(canvas.clientWidth * devicePixelRatio);
  canvas.height = Math.round(canvas.clientHeight * devicePixelRatio);
});

resizeObserver.observe(canvas);

For WebGL

const canvas = document.querySelector('canvas');
const gl = canvas.getContext('webgl');

const resizeObserver = new ResizeObserver(() => {
  canvas.width = Math.round(canvas.clientWidth * devicePixelRatio);
  canvas.height = Math.round(canvas.clientHeight * devicePixelRatio);
  gl.viewport(0, 0, canvas.width, canvas.height);
});

resizeObserver.observe(canvas);

Notice that we should take device pixel ratio into account, especially for HD-DPI display.

jeantimex
  • 1,619
  • 16
  • 14
  • As [the article in @gman’s answer](https://webglfundamentals.org/webgl/lessons/webgl-resizing-the-canvas.html) describes, using `canvas.clientWidth`/`canvas.clientHeight` solely doesn’t precisely reflect the actual numbers of physical device pixels (and the actual width/height ratio from them) that the `` element is taking up, so there might be minuscule visual distortion in the pixel aspect ratio of the canvas image. This could be improved with `Element.getBoundingClientRect()`, or better yet, `ResizeObserverEntry.devicePixelContentBoxSize`. – Константин Ван Nov 28 '22 at 22:23
0

I think this is what should we exactly do: http://www.html5rocks.com/en/tutorials/casestudies/gopherwoord-studios-resizing-html5-games/

function resizeGame() {
    var gameArea = document.getElementById('gameArea');
    var widthToHeight = 4 / 3;
    var newWidth = window.innerWidth;
    var newHeight = window.innerHeight;
    var newWidthToHeight = newWidth / newHeight;

    if (newWidthToHeight > widthToHeight) {
        newWidth = newHeight * widthToHeight;
        gameArea.style.height = newHeight + 'px';
        gameArea.style.width = newWidth + 'px';
    } else {
        newHeight = newWidth / widthToHeight;
        gameArea.style.width = newWidth + 'px';
        gameArea.style.height = newHeight + 'px';
    }

    gameArea.style.marginTop = (-newHeight / 2) + 'px';
    gameArea.style.marginLeft = (-newWidth / 2) + 'px';

    var gameCanvas = document.getElementById('gameCanvas');
    gameCanvas.width = newWidth;
    gameCanvas.height = newHeight;
}

window.addEventListener('resize', resizeGame, false);
window.addEventListener('orientationchange', resizeGame, false);
Arvind Bhardwaj
  • 5,231
  • 5
  • 35
  • 49
0
(function() {

    // get viewport size
    getViewportSize = function() {
        return {
            height: window.innerHeight,
            width:  window.innerWidth
        };
    };

    // update canvas size
    updateSizes = function() {
        var viewportSize = getViewportSize();
        $('#myCanvas').width(viewportSize.width).height(viewportSize.height);
        $('#myCanvas').attr('width', viewportSize.width).attr('height', viewportSize.height);
    };

    // run on load
    updateSizes();

    // handle window resizing
    $(window).on('resize', function() {
        updateSizes();
    });

}());
lokers
  • 2,106
  • 2
  • 18
  • 19
-1

This worked for me. Pseudocode:

// screen width and height
scr = {w:document.documentElement.clientWidth,h:document.documentElement.clientHeight}
canvas.width = scr.w
canvas.height = scr.h

Also, like devyn said, you can replace "document.documentElement.client" with "inner" for both the width and height:

**document.documentElement.client**Width
**inner**Width
**document.documentElement.client**Height
**inner**Height

and it still works.

Zayan
  • 49
  • 1
  • 3