0

I've created a simple canvas element

<canvas style="width:100%;height:100%;" id="canvas"></canvas>

when I try to get the height, however in javascript:

var canvas = document.getElementById(config.elementId);
console.log(canvas.height); //150
console.log(canvas.width); //300

console.log(canvas.style.height); //100%
console.log(canvas.style.width); //100%

If I inspect the element in chrome's debugger, and actually mouse over the element, chrome is reporting the element size as

1627x925px

How on earth do I get to the 1627x925px measurements in js?

Alex
  • 5,674
  • 7
  • 42
  • 65
  • 1
    See the last bit of the accepted answer to this question http://stackoverflow.com/questions/4938346/canvas-width-and-height-in-html5 – Musa Nov 23 '12 at 06:31

2 Answers2

1

As @Alex says, you can use the getComputedStyle function to get the current size of the canvas.

But... to make the canvas full screen width and height always, meaning even when the browser is resized, you need to run your draw loop within a function that resizes the canvas to the window.innerHeight and window.innerWidth.

Once you do that, you can use the normal canvas.height and canvas.width functions to get properly the canvas size:

(function() {
    var canvas = document.getElementById('canvas'),
    context = canvas.getContext('2d');

    // resize the canvas to fill browser window dynamically
    window.addEventListener('resize', resizeCanvas, false);

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

        /* Your drawings need to be inside this function
         * to avoid canvas to be cleared. */
        drawStuff(); 
    }
    resizeCanvas();

    function drawStuff() {
        console.log(canvas.height); //925
        console.log(canvas.width); //1627
        // do your drawing stuff here
    }
})();

Plus: Use this CSS hacks to make the canvas full size without problems:

/* remove the top and left whitespace */
* { margin:0; padding:0; } 

/* just to be sure these are full screen*/
html, body { width:100%; height:100%; }

/* To remove the scrollbar */
canvas { display:block; } 
Tomas Ramirez Sarduy
  • 17,294
  • 8
  • 69
  • 85
0

We can spy on the computed styles!

document.defaultView.getComputedStyle(canvas).height
document.defaultView.getComputedStyle(canvas).width
Alex
  • 5,674
  • 7
  • 42
  • 65