B. Freeman B. Freeman - 1 month ago 20
HTML Question

How to resize the canvas using JavaScript?

How would one make the JavaScript canvas (or whatever the 400px by 400px drawing area is called) larger than 400x400?

I have a 1440p screen and when I run my JS files through an HTML file, the canvas is not surprisingly a small 400px by 400px box in the top left.

Is there anything I can do to expand the canvas to a specified height and width?

Answer

The following jsfiddle demonstrates how to resize the canvas. https://jsfiddle.net/jaredwilli/qFuDr/

(function() {
        var canvas = document.getElementById('canvas'),
                context = canvas.getContext('2d');

        // resize the canvas to fill browser window dynamically
        window.addEventListener('resize', resizeCanvas, false);
        
        function resizeCanvas() {
                canvas.width = window.innerWidth;
                canvas.height = window.innerHeight;
                
                /**
                 * Your drawings need to be inside this function otherwise they will be reset when 
                 * you resize the browser window and the canvas goes will be cleared.
                 */
                drawStuff(); 
        }
        resizeCanvas();
        
        function drawStuff() {
                // do your drawing stuff here
        }
})();