<!DOCTYPE html>
<
html
lang
=
"en"
>
<
head
>
<
meta
charset
=
"UTF-8"
>
<
meta
name
=
"viewport"
content
=
"width=device-width, initial-scale=1.0"
>
<
title
>
How to create canvas of the same
size as a div in a grid?
</
title
>
<
style
>
.grid-container {
display: grid;
grid-template-columns: 100%;
grid-template-rows: 100px;
height: 100%;
width: 100%;
text-align: center;
}
.canvas-container {
width: 300px;
height: 500px;
margin: auto;
}
.grid-canvas {
background-color: transparent;
}
#btn {
color: #fff;
background-color: green;
height: 30px;
width: 150px;
border-radius: 5px;
border: none;
}
</
style
>
</
head
>
<
body
>
<
div
class
=
"grid-container"
>
<
div
class
=
"canvas-container"
>
This is canvas container with
height: 500px and width: 300px
<
canvas
class
=
"grid-canvas"
></
canvas
>
</
div
>
<
div
class
=
"text-container"
>
<
h2
style
=
"color: green;"
>
GeeksforGeeks
</
h2
>
<
h3
>
Click the below button to get the height
and <
br
/> width of the canvas element.
</
h3
>
<
button
id
=
"btn"
>
Get height and width
</
button
>
<
p
id
=
"result"
></
p
>
</
div
>
</
div
>
<
script
src
=
integrity
=
"sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g=="
crossorigin
=
"anonymous"
referrerpolicy
=
"no-referrer"
>
</
script
>
<
script
>
$(document).ready(() => {
const myDiv = $('.canvas-container')[0];
const myCanvas = $('.grid-canvas');
myCanvas.width = myDiv.offsetWidth;
myCanvas.height = myDiv.offsetHeight;
$('#btn').click(function () {
if (myDiv.offsetWidth === myCanvas.width &&
myDiv.offsetHeight === myCanvas.height)
{
$('#result').html(`
Grid Div width: <
strong
>${myDiv.offsetWidth}</
strong
>,
Grid Div Height: <
strong
>${myDiv.offsetHeight}</
strong
><
br
/>
Canvas Width: <
strong
>${myCanvas.width}</
strong
>,
Canvas Height: <
strong
>${myCanvas.height}</
strong
>`)
}
});
});
</
script
>
</
body
>
</
html
>