I’m trying to build a simple hangouts app which uses a canvas. The issue I have is that whenever I try to get the height and width of the canvas I get 0. When I copy the exact same code in a test file (test.html) everything seems to work fine. This is my code, I’ve put all the css and html in one place to make it easier to read:
<script src="https://hangoutsapi.talkgadget.google.com/hangouts/_/api/hangout.js?v=1.2"> </script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="canvasDiv"></div>
<style>
#canvasDiv {
width:100%;
height:100%;
position:relative;
}
</style>
<script>
$(window).load(function(){
var canvasDiv = document.getElementById('canvasDiv');
canvas = document.createElement('canvas');
canvas.style.width='100%';
canvas.style.height='100%';
canvasDiv.appendChild(canvas);
console.log($('#canvasDiv').height());
canvas.width = $('#canvasDiv').width();
canvas.height = $('#canvasDiv').height();
In the previous code the console.log prints 0 in the google hangouts iframe, but prints the correct number in the test file.
Setting percentages is iffy at best. In my experience I much rather prefer just to use a JavaScript function to get the page width and height, and set the div dimensions to pixels, not percents.
This function will get the height and width of the browser. Replace your
<body>tag withand this function will be called when the page loads and called again every time the page is resized (to update the dimensions of the
<div>.) In this way you’ll have actual pixels for the dimensions, not percentages.Try it and let me know if you have problems. I’ve used this script many times in my coding history, and it’s become one of my favorites and most used.