Reputation: 10089
I have a problem to get my window size, I try this code:
Javascript
var game;
function game() {
this.canvas = document.getElementById('canvas');
this.canvasWidth = window.innerWidth;
this.canvasHeight = window.innerHeight;
this.initCanvas = function() {
this.canvas.style.width = this.canvasWidth + "px";
this.canvas.style.height = this.canvasHeight + "px";
}
this.run = function() {
this.initCanvas();
}
}
game = new game();
game.run();
I also have
CSS
html, body {
padding: 0;
margin: 0;
}
I only have a canvas in my body.
Problem is, that I have a vertical and horizontal scroll bar. This means the size of canvas is too large. How to make it of the window size without the scroll bars appearing?
Upvotes: 0
Views: 900
Reputation: 27405
When you use CSS to style your <canvas>
element it will get scaled instead of sized. Be sure to set the .width
and .height
properties on the canvas
element instead (ie canvas.width
not canvas.style.width
).
In the example the first canvas element is scaled correctly, the second (using CSS) is not scaled properly. This has to do with a default canvas element size (300x150) that CSS scales.
To prevent getting scrollbars when setting the <canvas>
to the full window width/height set the body
to overflow:hidden;
as used in the jsfiddle above.
Upvotes: 2
Reputation: 15794
It looks like you're just trying to make your canvas have a width and height of 100%. You can do this with just css:
HTML
<body>
<canvas id="canvas"></canvas>
</body>
CSS
body, html {
height: 100%;
width: 100%;
margin: 0px;
}
canvas {
background: #ffcccc;
height: 100%;
width: 100%;
display: block;
}
Or if you want to use your code but get rid of the scroll bars on the window, you need to specify block
on the canvas tag.
CSS
canvas {
display: block;
}
Upvotes: 3