Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a HTML5 canvas fit dynamic parent/flex box container

Tags:

Is there a way I can create a canvas inside a dynamic re-sizing flex-box container?

Preferably a CSS only solution but I think JavaScript is required for redraw?

I think one solution could be to listen to the re-sizing event and then scale the canvas to meet the size of the flex box parent then force a redraw but I would preferably like to use as much CSS as possible or a more clean/less code solution.

The current approach is CSS based where the canvas is re-sized according to the parent flex box element. The graphics are blurred, re positioned and overflowed from the canvas in the below screenshot.

Stretched image/Graphics overflowing canvas

CSS:

html,body{
            margin:0;
            width:100%;
            height:100%;
        }
        body{
            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;
        }

HTML:

<header>
</header>
<main>
    <canvas id="stage"></canvas>
</main>

Javascript:

$( document ).ready(function() {
    var ctx = $("#stage")[0].getContext("2d");
    ctx.strokeStyle="#FFFFFF";
    ctx.beginPath();
    ctx.arc(100,100,50,0,2*Math.PI);
    ctx.stroke();
});

JS fiddle showing the issue: https://jsfiddle.net/h2v1w0a1/