Skip to content Skip to sidebar Skip to footer

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 d

Solution 1:

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;
  }
<canvasid="canvas"style="height: 100%; width:100%;"></canvas>

Post a Comment for "Does Using Percentages Instead Of Pixels Change An Html 5 Canvas Change Its Properties?"