devyn devyn - 1 year ago 152
Javascript Question

Resize HTML5 canvas to fit window

How can I automatically scale the HTML5

element to fit the page?

For example, I can get a
to scale by setting the
properties to 100%, but a
won't scale, will it?

Answer Source

I believe I have found an elegant solution to this:


/* 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...


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

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