Dynamically resize canvas window - Javascript Canvas

Javascript examples for Canvas:Example

Description

Dynamically resize canvas window

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://code.jquery.com/jquery-1.8.3.js"></script> 
      <style id="compiled-css" type="text/css">

canvas {//  w ww  . j a  v  a  2 s  . co  m
   border: 1px dotted black;
   background: blue;
}


      </style> 
      <script type="text/javascript">
    $(window).load(function(){
(function() {
    getPercentageOfWindow = function() {
        var viewportSize = getViewportSize();
        var canvasSize = getCanvastSize();
        return {
            x: canvasSize.width / (viewportSize.width - 10),
            y: canvasSize.height / (viewportSize.height - 10)
        };
    };
    getCanvasContext = function() {
        return $("#myCanvas")[0].getContext('2d');
    };
    getViewportSize = function() {
        return {
            height: window.innerHeight,
            width: window.innerWidth
        };
    };
    getCanvastSize = function() {
        var ctx = getCanvasContext();
        return {
            height: ctx.canvas.height,
            width: ctx.canvas.width
        };
    };
    // update canvas size
    updateSizes = function() {
        var viewportSize = getViewportSize();
        var ctx = getCanvasContext();
        ctx.canvas.height = viewportSize.height * percentage.y;
        ctx.canvas.width = viewportSize.width * percentage.x;
    };
    var percentage = getPercentageOfWindow();
    $(window).on('resize', function() {
        updateSizes();
    });
}());
    });

      </script> 
   </head> 
   <body> 
      <canvas id="myCanvas" width="300" height="300">  
      </canvas>
   </body>
</html>

Related Tutorials