How to use the offsetWidth and offsetHeight properties In Javascript
The offsetWidth and offsetHeight properties can also be used to create a canvas of the same size as a div in the grid.
Syntax:
const variableName = $('canvas_selector');
variableName.width = $('div_selector').offsetWidth;
variableName.height = $('div_selector').offsetHeight;
Example: The below code example uses the offsetWidth and offsetHeight properties to create a canvas of same size as a div in the grid.
HTML
<!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;" > w3wiki </ 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 > <!-- jQuery CDN Link --> < script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" integrity = "sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==" crossorigin = "anonymous" referrerpolicy = "no-referrer" > </ script > <!-- Custom 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 > |
Output:
How to Create Canvas of the Same Size as a Div in a Grid ?
In jQuery, we have different methods and properties available to create a canvas element of the same size as that of a div in the grid.
These are the following approaches:
Table of Content
- Using the get(), height(), and width() methods
- Using the offsetWidth and offsetHeight properties