Sammy Kumar
Sammy Kumar

Reputation: 121

Sizing HTML5 canvas to browser width

Not sure why I can't figure this out but I am trying to draw a rectangle using HTML5 canvas. The height is predefined. However i want the width to be 100% of the browser. I've been using code examples from here but nothing has worked so far.

CSS

<style type="text/css">
body { 
    background:#414141;
    width:100%;
    margin:0px;
    display:block;
}

html {
    width:100%;
    display:block;
    margin:0px;
}

</style>

HTML & Javascript

<canvas id="navBar" style="display:block; width=100%"></canvas>
<script>
var c = document.getElementById("navBar");
var ctx = c.getContext("2d");
ctx.fillStyle = "#262626";
ctx.fillRect(0,0,navBar.width,125);
</script>

instead of navbar.width I have tried screen.width and window.innerWidth neither one works. Any ideas or suggestions to do this better?

Upvotes: 0

Views: 84

Answers (4)

toastrackengima
toastrackengima

Reputation: 8722

Try:

c.width = screen.width;

Explaination:

  • screen.width is a global variable which stores the screens current width.
  • This code sets the width property of the canvas (c.width) to that value.

Also note that there is another global variable, screen.height which stores the screens' current height. This can be set in a similar manner.

Upvotes: 0

Joshua
Joshua

Reputation: 946

This works:

c.style.width=window.innerWidth;

Of course, this has the problem that if the browser resizes the window, the canvas will either be too big or too small. So we can attach an event listener and wait for a resize like this:

c.style.width=window.innerWidth;

window.addEventListener("resize", function(){
    c.style.width=window.innerWidth;    
}, false);

Upvotes: 0

EvilZebra
EvilZebra

Reputation: 1072

First, change your canvas to <canvas id="navBar" style="width:100%"></canvas>

Then just get the width of the <canvas> element.

var c = document.getElementById("navBar");
var ctx = c.getContext("2d");
var width = c.width;

ctx.fillStyle = "#262626";
ctx.fillRect(0,0,width,125);

jsfiddle

Upvotes: 0

Sammy Kumar
Sammy Kumar

Reputation: 121

Oops I put too many quotes here

<canvas id="navBar" style="display:block;" width="100%"></canvas>

should be

<canvas id="navBar" style="display:block; width=100%"></canvas>

Upvotes: 2

Related Questions