views:

170

answers:

2

I'll post a link since theres to much to post here:

http://hem.bredband.net/noor/canvas.htm

My goal is to make the picture fit inside the window with the width of the image being the same as the window, even after resize. If the pictures height becomes to big for the window then the picture should resize itself according to the height and not the width.

Somewhere along my code there is something wrong.. forgive me if this is stupid, i am still learning..

Thanks!

A: 

As far as I know. You only want to make one call to getContext(). I didn't really analyze the code very much past this point though.

Shaunwithanau
+2  A: 

I think this is the behavior you are trying to achieve. I refactored it so you only need to create one Image object (and changed the variable names to English so I could follow the code easier). Hopefully it's clear how the code works. Feel free to ask in the comments if you have any questions about it. The body onload property will need to be changed to "setupBackground();" instead of "draw();" to work with this code.

function setupBackground() {
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');

    function draw() {
        canvas.width = 0;
        canvas.height = 0;
        var divHeight = div.scrollHeight;
        var divWidth = div.scrollWidth;
        var yScale = divHeight / img.height;
        var xScale = divWidth / img.width;

        var newImgHeight = img.height * xScale;
        var newImgWidth = divWidth;

        if (divHeight >= newImgHeight) {
            newImgHeight = divHeight;
            newImgWidth = img.width * yScale;
        }

        canvas.width = divWidth;
        canvas.height = divHeight;
        ctx.drawImage(img,0,0,newImgWidth,newImgHeight);
    }

    var img = new Image();
    img.onload = function() {
        window.onresize = draw;
        draw();
    }
    img.src = 'ad.jpg';
};
Matthew Crumley