Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Canvas size inside CSS grid

What I Have:

A simple website testing the grid display of css. And a canvas element that is supposed to fill the div element with id "content" (snippet below)

What is the problem:

As soon as I add the canvas element, the grid system proportions aren't correct anymore. You can test and see it for yourself in the snippet below by just removing the canvas element and placing it back.

What I have tried:

  • I have tried to fix this by adding a width and height to the css, this resulted in a stretched out canvas. For example: If I were to draw a square it would become a rectangle in the canvas (due to stretching).
  • I tried assigning a canvas.width and canvas.height. But it still doesn't fill the whole div element.

Question:

How can I make the canvas fill up the whole grid area "content", without stretching the canvas and without taking the grid itself out of proportion?

Extra

Thank you for your time.

var canvas = document.querySelector("#canvas");
var div = document.getElementById("header");
var div2 = document.getElementById("content");

canvas.width = div2.clientWidth;
canvas.height = div2.clientHeight;
canvas{
    background: green;
}
.site
{
    width: 100%;
    height: 100%;
    display: grid;
    grid-template-rows: 33%, auto, 33%;
    grid-template-columns: 33%, auto, 33%;
    grid-template-areas:
        "header header navbar"
        "c c sidebar"
        "footer footer footer";
}
#header
{
    grid-area: header;
    background: rgb(255, 0, 0);
}
#navbar
{
    grid-area: navbar;
    background: rgb(255, 238, 0);
}
#content
{
    grid-area: c;
    background: rgb(60, 255, 0);
}
#sidebar
{
    grid-area: sidebar;
    background: rgb(0, 98, 255);
}
#footer
{
    grid-area: footer;
    background: rgb(255, 0, 234);
}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>CssGrid</title>
</head>
<body>
    <div class="site">
        <div id="header">header</div>
        <div id="navbar">navbar</div>
        <div id="content">
            <canvas id="canvas"></canvas>
        </div>
        <div id="sidebar">sidebar</div>
        <div id="footer">footer</div>
    </div>
</body>
</html>

What it does What it does What it should do What it should do

like image 714
Kevin Avatar asked Nov 05 '17 22:11

Kevin


1 Answers

Try this if it works for you:

CSS:

#content {
    grid-area: c;
    background: rgb(60, 255, 0);
    position: relative;
}

canvas {
    background: green;
    position: absolute;
    height: 100%;
    width: 100%;
}
like image 118
Cons7an7ine Avatar answered Oct 07 '22 01:10

Cons7an7ine