make a HTML5 canvas fit dynamic parent/flex box container - Javascript Canvas

Javascript examples for Canvas:Example

Description

make a HTML5 canvas fit dynamic parent/flex box container

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-2.1.3.js"></script> 
      <style id="compiled-css" type="text/css">

html,body{
   margin:0;
   width:100%;
   height:100%;
}
body{// www.  j a  v a 2s  .  c  om
   display:flex;
   flex-direction:column;
}
header{
   width:100%;
   height:40px;
   background-color:red;
}
main{
   display:flex;
   flex: 1 1 auto;
   border: 1px solid blue;
   width:80vw;
}
canvas{
   /*flex: 1 1 auto;*/
   background-color:black;
}


      </style> 
      <script type="text/javascript">
    $(window).load(function(){
var canvas = $("#stage")[0];
var ctx = canvas.getContext("2d");
draw();
function draw() {
    setCanvasSize(ctx.canvas);
    ctx.strokeStyle="#FFFFFF";
    ctx.beginPath();
    ctx.arc(100,100,50,0,2*Math.PI);
    ctx.stroke();
}
$(window).on("resize", draw);
function setCanvasSize(canvas) {
    var parent = canvas.parentNode,
        styles = getComputedStyle(parent),
        w = parseInt(styles.getPropertyValue("width"), 10),
        h = parseInt(styles.getPropertyValue("height"), 10);
    canvas.width = w;
    canvas.height = h;
}
    });

      </script> 
   </head> 
   <body> 
      <header> 
      </header> 
      <main> 
         <canvas id="stage"></canvas> 
      </main>  
   </body>
</html>

Related Tutorials