nbobito12
nbobito12

Reputation: 33

Does using percentages instead of pixels change an html 5 canvas change its properties?

I am practicing javascript and I am trying to make a game. I want the canvas element to be fullscreen, so I used percentages for the height and width attribute, but when I do, it doesn't behave like it normally does. When I run my debug code, it is supposed to make a box that is 50px by 50px, but the graphics look bigger than normal.

I've tried getting the canvas height and width in pixels, but that did not work. It does not report any error messages, but it is still too big.

<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <canvas id="canvas" style="height: 100%; width:100%;"></canvas>
  </body>
<style>
    html, body {width: 100%; 
    margin: 0;
    height: 100%;
    overflow: hidden;
    position:fixed;}
</style>
<script>
  var canvas = document.getElementById("canvas")
  var c = canvas.getContext("2d")

  c.fillStyle = "#FFFF00"
  c.fillRect(50,50,50,50)
</script>

There are no error messages none appearing, but it is not sized correctly, and I can't figure out why it's not working.

Upvotes: 3

Views: 871

Answers (1)

traktor
traktor

Reputation: 19344

It makes a difference if canvas size is set in CSS or using element attributes.

The canvas element size is set by its width and height attributes (as numbers). This sets the number of addressable pixels used to store the canvas drawing in memory. In the absence of width and height attributes, canvas element dimensions are set to 300 by 150 (pixels) by default.

CSS applied to the canvas can scale its dimensions using software interpolation of the canvas treated as an image. Just as a small image looks bigger when scaled to full screen, both the 300 by 150 pixel canvas and objects drawn within it (using canvas pixel coordinates) appear larger when blown up.

To make canvas coordinates match the screen size in pixels, set its width and height attributes to pixel number values. E.G.

  var canvas = document.getElementById("canvas")
  var c = canvas.getContext("2d")

  c.fillStyle = "#FFFF00"
  c.fillRect(50,50,50,50)
  console.log( canvas.width, canvas.height);
  alert( "fix?" )
  canvas.style="";  // remove CSS scaling
  canvas.width = document.body.clientWidth;
  canvas.height = document.body.clientHeight;
  c.fillStyle = "#FFFF00"
  c.fillRect(50,50,50,50)
  body {
    width: 100%; 
    margin: 0;
    height: 100%;
    background-color: honeydew;
    overflow: hidden;
    position:fixed;
  }
  canvas {
    background-color: silver;
  }
    <canvas id="canvas" style="height: 100%; width:100%;"></canvas>

Upvotes: 3

Related Questions