views:

310

answers:

1

I'm trying to get a canvas element to take up the entirety of the document height and window width, so that when I resize the window, the canvas element stretches with it, in effect, giving me a full screen canvas. What is actually happening, though, is the document height(and consequently, the canvas height) increases no matter how the window is resized.

I'm using this code:

$(document).ready(function () {
    $("#wrapper").before("<div id='background'><canvas id='depth' width='"+$(window).width()+"'height='"+$(document).height()+"'></canvas></div>");
    $(window).resize(function() {
        $("#depth").attr("width",$(window).width());
        $("#depth").attr("height",$(document).height());
    });
});

I've also tried using DOM scripting with the exact same result. Is this a quirk of resizing canvas elements, or am I missing something?

Here is the problem in action

+1  A: 

I think this should work? It's adapted from code I wrote to ensure #wrapper always stretched to reach the bottom of the screen if the content didn't already make it do so (but I removed the minimum height constraints). I'm sure you can adapt this to your needs for width as well.

The summary of where you were going wrong is in the maths to calculate what the height should be in the event of the window being negatively resized.

I've also left in a couple of extra bits that you can see which deal with some browser inconsistencies when calculating window height; solved a couple of bugs I found.

$(document).ready(function() {resize()});
$(window).resize(function() {resize()});

// Calculate Required Wrapper Height
function resize() {
    // I think this is for Opera's benefit?
    var viewportHeight = window.innerHeight ? window.innerHeight : $(window).height();

    // IE7
    if (jQuery.browser.msie) {
        if(parseInt(jQuery.browser.version) == 7) {
            viewportHeight -= 3;
        }
    }

    if($('#wrapper').height() > viewportHeight) {
        $('.content').height($('#wrapper').height() - viewportHeight);
    }

    if($('#wrapper').height() < viewportHeight) {
        $('.content').height(viewportHeight - $('#wrapper').height());
    }
}
Steve
That worked beautifully, with some modifications. Thanks for the help!
Rob