Canvas width and height calculation is off - javascript

I'm using some script I found on Git that generates a snow effect. Somewhere in the code I have to set the width and the height of the canvas in which the snow is generated. I'm setting the canvas to the window full width / height :
canvas.width = $(window).width();
canvas.height = $(window).height();
But when rendered in the browser there are on both height and width some extra pixels adding scrollbars to the window. You can see the behavior here : Canvas ; I'm not quite sure why the width / height is calculated wrong or if there's something else interfering with those calculations that it makes it bigger than the actual window width / height. Maybe someone has a different view of the behavior or encountered it before ?

The canvas element is displayed inline by default, you can read here about similar problem.
The solution is quite simple :) Add following css code to the canvas element:
display: block;
and scrollbars should disappear.
old answer:
$(window).width() works properly but i don't know why $(window).height() returns too large value. It cause also showing vertical scrollbar because earlier computed width don't include the size of horizontal scrollbar.

Related

Get the max-viewport size of user browser window

I am working on a project including several draggable divs using jQuery-UI with the constrain functionality to help the user avoid stray divs hiding in the outskirts.
Now I am getting the full screen dimensions for the constrains:
var width = window.screen.availWidth;
var height = window.screen.availHeight;
And that is pretty close to what I desire. However, as all browser have the tabs and search input line on the top and often some other stuff at the bottom I am getting a bigger constrain than the actual view port. Then you say get the view port dimensions:
$(window).height();
$(window).width();
Well, that is close to but it is not 100%, because if the user has a minimized window when entering the site that view port size is going to be the constrain size. This means that if the user then uses full screen the constraint is just as big as the view port were from the start.
Then you might say: "Why not change the constrain dynamically along the way?"
Well, that could have been a possibility but this whole page idea is to fine tune the GUI and by changing the constrain size could potentially mess upp the positioning of the draggable objects. So, what am I asking for?
I am asking for a way to get the maximum browser view port size on the current users screen? No matter if the user has a smaller than max browser window ATM when entering the page.
PS. I suppose I could check which browser the user is using and by hard code remove the amount of pixels that specific browsers head-bar is using. That however is a bad solution in my book, for several reasons.
with some good suggestions pointing me in the right direction I have now understood my problem.. I think.
These two bad boys are actually doing the trick:
var width = window.screen.availWidth;
var height = window.screen.availHeight;
BUT!! I am on a desktop running windows and the taskbar at the bottom is actually overlaying the chrome browser window! This was what made me confused to start with. So... yeah. I guess that is it. I just have to live with my users beeing able to put the divs under the win taskbar. Well ok! Bye
var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
Although pretty hacky, you could take advantage of the viewport units of css.
$('body').css({
'height': '100vh',
'width': '100vw'
});
var height = $('body').height(); // or innerHeight or OuterHeight
var width = $('body').width();
vw : Relative to 1% of the width of the viewport
vh : Relative to 1% of the height of the viewport
vmin : Relative to 1% of viewport's smaller dimension
vmax : Relative to 1% of viewport's larger dimension
https://www.w3schools.com/cssref/css_units.asp
You can use $(window).outerWidth() and $(window).outerHeight()
You may refer these links.
https://developer.mozilla.org/en-US/docs/Web/API/Window/outerHeight
https://developer.mozilla.org/en-US/docs/Web/API/Window/outerWidth

change image manually as window sizes

I used js to set image width and height according to window size. But in some cases when the browser is very wide, the image's hight exceeds all its father element's height. As a result, the bottom part of the image is not shown. How can I solve this?
I used bootstrap and swiper in this project and the image I want to change is inside my swiper division. I set and all the image's father elements' height to 100%. Here is my js code to change is image dymanically. The image size is 2560*1440.
if(winWidth/winHeight < 2560/1440) {
imgHeight = winHeight;
imgWidth = winHeight/1440 * 2560;
}else {
imgWidth = winWidth;
imgHeight = winWidth/2560 * 1440;
}
attr = "width:" + imgWidth + 'px;height:' + imgHeight + 'px;margin-left: -' + imgWidth/2 + 'px;margin-top:-' + imgHeight/2 + 'px';
$('.main .swiper-slide > img').attr('style',attr);
PS:
Sorry I didn't make it clear. The following methods you provided scale the image down in vertical view and so leaves much blank in the page. Actually I want my image's height to occupy the whole window's height, no matter in vertical window or horizontal window. And if the window is wide enough, image's width equals the window's width, otherwise cut the image in width and make it equals the window's width too.
#patstuart is correct, this is much better handled directly through CSS. It's pretty amazing how many styling issues (go figure) can be solved without writing a single line of JavaScript. So to answer your second question, let's figure out how it can be done with CSS. Without seeing a fiddle or your actual page / image, I'll just shoot from the hip here. If I understand correctly, you want the full image to display at its correct ratio no matter what the width / height of the screen is. If that's the case, here's a nice little trick:
.main .swiper-slide {
width: 100%;
height: 0;
/* Padding bottom should be the height's ratio to the width.
Which in this case, would be 56.25% */
padding-bottom: 56.25%;
}
.main .swiper-slide > img {
width: 100%;
}
That is how aspect ratio can be handled with CSS. Let me know if that resolves your issue or if you have any other questions. CSS was made for styling so always look for a solution there first.

jQuery window resize issue - height/width calculation

The issue is as such - I'm using jQuery to set the height of a container. I am using the plugin bgStretcher 3.1.2 to stretch an image to the dimensions of this container. In screenshot 1 the container I am reffering to is the area occupied y the brick wall image.
The problem arises when you resize the browser, every 2nd time the resize fires the calculations for height/width are off by 15px (I have no idea where this number comes from), creating a gap to the right and bottom of the container as visible in Screenshot 2. This screenshot also includes the console readings of the height of the container as returned by Jquery, indicating the issue. So when you resize the container jitters like hell and potentially ends up with the aforementioned gap.
I believe there is some sort of conflict happening between my code and the plugin as they're both bound to window resize.
This is the simple bit of code I'm using on my end:
win.resize(function() {
console.log(win.height());
conH = win.height()-68;
wrapper.css({
height: conH+"px"
})
}).resize();
function init_heght(element) {
var y = $(window).height();
$(element).css('height', y);
};
init_heght('#section-left-menu');

jQuery/JS, iOS 4 and $(document).height() problems

I've run into an odd issue with what appears to be various versions of Webkit browsers. I'm trying to position an element on the center of the screen and to do the calculations, I need to get various dimensions, specifically the height of the body and the height of the screen. In jQuery I've been using:
var bodyHeight = $('body').height();
var screenHeight = $(window).height();
My page is typically much taller than the actual viewport, so when I 'alert' those variables, bodyHeight should end up being large, while screenHeight should remain constant (height of the browser viewport).
This is true in
- Firefox
- Chrome 15 (whoa! When did Chrome get to version 15?)
- Safari on iOS5
This is NOT working in:
- Safari on iOS4
- Safari 5.0.4
On the latter two, $(window).height(); always returns the same value as $('body').height()
Thinking it was perhaps a jQuery issue, I swapped out the window height for window.outerHeight but that, too, does the same thing, making me think this is actually some sort of webkit problem.
Has anyone ran into this and know of a way around this issue?
To complicate things, I can't seem to replicate this in isolation. For instance: http://jsbin.com/omogap/3 works fine.
I've determined it's not a CSS issue, so perhaps there's other JS wreaking havoc on this particular browser I need to find.
I've been fighting with this for a very long time (because of bug of my plugin) and I've found the way how to get proper height of window in Mobile Safari.
It works correctly no matter what zoom level is without subtracting height of screen with predefined height of status bars (which might change in future). And it works with iOS6 fullscreen mode.
Some tests (on iPhone with screen size 320x480, in landscape mode):
// Returns height of the screen including all toolbars
// Requires detection of orientation. (320px for our test)
window.orientation === 0 ? screen.height : screen.width
// Returns height of the visible area
// It decreases if you zoom in
window.innerHeight
// Returns height of screen minus all toolbars
// The problem is that it always subtracts it with height of the browser bar, no matter if it present or not
// In fullscreen mode it always returns 320px.
// Doesn't change when zoom level is changed.
document.documentElement.clientHeight
Here is how height is detected:
var getIOSWindowHeight = function() {
// Get zoom level of mobile Safari
// Note, that such zoom detection might not work correctly in other browsers
// We use width, instead of height, because there are no vertical toolbars :)
var zoomLevel = document.documentElement.clientWidth / window.innerWidth;
// window.innerHeight returns height of the visible area.
// We multiply it by zoom and get out real height.
return window.innerHeight * zoomLevel;
};
// You can also get height of the toolbars that are currently displayed
var getHeightOfIOSToolbars = function() {
var tH = (window.orientation === 0 ? screen.height : screen.width) - getIOSWindowHeight();
return tH > 1 ? tH : 0;
};
Such technique has only one con: it's not pixel perfect when page is zoomed in (because window.innerHeight always returns rounded value). It also returns incorrect value when you zoom in near top bar.
One year passed since you asked this question, but anyway hope this helps! :)
I had a similar problem. It had to do with 2 thing:
Box-sizing CSS3 property:
In the .height() jQuery documentation I found this:
Note that .height() will always return the content height, regardless of the value of the CSS box-sizing property. As of jQuery 1.8, this may require retrieving the CSS height plus box-sizing property and then subtracting any potential border and padding on each element when the element has box-sizing: border-box. To avoid this penalty, use .css( "height" ) rather than .height().
This may apply to $('body').height().
Document ready vs Window.load
$(document).ready() is run when the DOM is ready for JS but it's possible that images haven't finished loading yet. Using $(window).load() fixed my problem. Read more.
I hope this helps.
It is 2015, we are at iOS 8 now. iOS 9 is already around the corner. And the issue is still with us. Sigh.
I have implemented a cross-browser solution for the window size in jQuery.documentSize. It stays clear of any kind of browser sniffing and has been heavily unit-tested. Here's how it works:
Call $.windowHeight() for the height of the visual viewport. That is the height of the area you actually see in the viewport at the current zoom level, in CSS pixels.
Call $.windowHeight( { viewport: "layout" } ) for the height of the layout viewport. That is the height which the visible area would have at 1:1 zoom - the "original window height".
Just pick the appropriate viewport for your task, and you are done.
Behind the scenes, the calculation roughly follows the procedure outlined in the answer by #DmitrySemenov. I have written about the steps involved elsewhere on SO. Check it out if you are interested, or have a look at the source code.
Try this :
var screenHeight = (typeof window.outerHeight != 'undefined')?Math.max(window.outerHeight, $(window).height()):$(window).height()
A cross browser solution is set that by jQuery
Use this property:
$(window).height()
This return a int value that represents the size of visible screen height of browser in pixels.

Setting the minimum size of a JavaScript popup window

Is there any way to set the minimum size of a popup window through JavaScript?
My problem is that when someone makes it as small as he can the content just looks stupid.
When creating pop-ups, you can only set width and height. But since the pop-up was created, it means you can change the height and width of the window when the pop-up loads.
Simply place an onload event inside your pop-up window:
window.onload = function() {
if (document.body.scrollHeight) {
var winWidth = document.body.scrollWidth;
var winHeight = document.body.scrollHeight;
} else if (document.documentElement.scrollHeight) {
var winHeight = document.documentElement.scrollHeight;
var winWidth = document.documentElement.scrollWidth;
} else {
var winHeight = document.documentElement.offsetHeight;
var winWidth = document.documentElement.offsetWidth;
}
window.resizeTo(winWidth, winHeight);
}
edit: Tested in IE7,8, Chrome, Safari 4, Firefox 3. Working, but you might need to take into account the size of menu+address bars and such, as the window size will be the outer size, and this function will find the size of the content. So to be safe you should probably add a couple of pixels, and also turn off scrollbars in the popup to make sure they won't take up any space.
I do not believe that you can set a minimum using the Javascript new window. I know you can set the size and disable the scroll bars and prevent resizing, but that would answer the minimum, but also impose a maximum as well, which you may not be wanting.
Most browsers have a minimum width and height.
Internet Explorer 7
minimum width > 250px
minimum height > 150px
When using windows.open, you can specify the height and width of the window like this:
window.open ("http://www.stackoverflow.com",
"mywindow","menubar=1,resizable=1,width=350,height=250");
It is not the minimum size though, as the window will not be bigger when there is more room. You would have to check screen space yourself for that.
http://www.htmlgoodies.com/beyond/javascript/article.php/3471221
As seen in the link, you can set the minimum size. If you want to scale it so it gets bigger you must to that from within the popupwindow.

Categories