thomasdowell
thomasdowell

Reputation: 57

Update canvas dimensions as window is reshaped.

I have a HTML canvas set to the height and width of the window in JavaScript. However, if the window is reshaped, the canvas size stays the same unless the page is refreshed.

Upvotes: 1

Views: 3085

Answers (2)

James Taylor
James Taylor

Reputation: 6258

You probably want to create a Javascript window resize listener to set the size of the canvas programmatically when the window size has been changed.

window.onresize = function(event) {
    var canvas = document.getElementById('canvas');
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    redraw(); // you must handle the redraw yourself
};

You will just have to adjust the width and height of the canvas, making sure you redraw() in a custom method.

Check out this basic JSFiddle to show a basic implementation of this.

Of note:

You can set the CSS height and width of a canvas element, which works as expected.

canvas {
    width: 50%;
}

The issue with doing is that if you specify both a width and height, this can create distortion in whatever is drawn on the canvas. If you only specify one property, however, the canvas will scale proportionally. Depending on the use case for your canvas, this might be an okay way of going about doing it.

Upvotes: 0

Shifa Khan
Shifa Khan

Reputation: 779

To dynamically resize the canvas, you can add an event listener to check if the window has been resized. Then you can redraw your canvas.

        function initialize() {
            // Register an event listener to
            // call the resizeCanvas() function each time 
            // the window is resized.
            window.addEventListener('resize', resizeCanvas, false);

            // Draw canvas border for the first time.
            resizeCanvas();
        }

        // Display custom canvas.
        // In this case it's a blue, 5 pixel border that 
        // resizes along with the browser window.                   
        function redraw() {
            context.strokeStyle = 'blue';
            context.lineWidth = '5';
            context.strokeRect(0, 0, window.innerWidth, window.innerHeight);
        }

        // Runs each time the DOM window resize event fires.
        // Resets the canvas dimensions to match window,
        // then draws the new borders accordingly.
        function resizeCanvas() {
            htmlCanvas.width = window.innerWidth;
            htmlCanvas.height = window.innerHeight;
            redraw();
        }

For further details on how this works, here's an excellent blog post that lists out all steps - http://htmlcheats.com/html/resize-the-html5-canvas-dyamically/

Upvotes: 1

Related Questions