math4tots
math4tots

Reputation: 8870

Getting window dimensions in a Metro app

How do I get the dimensions of the window in a windows 8 metro app?

I want to fill the screen with a canvas element, and currently my default.js file looks something like this

// ... some autogenerated code ...
app.onactivated = function (args) {
    if (args.detail.kind === activation.ActivationKind.launch) {
    // ... some autogenerated code ...

    var canvas = document.getElementById("myCanvas");
    var context = canvas.getContext("2d");

    canvas.width  = 600;  // I want to set width and height here so that
    canvas.height = 800;  // canvas fills the entire screen/window.
};
// ... more autogenerated code ...

Upvotes: 1

Views: 1942

Answers (3)

Farshid T
Farshid T

Reputation: 2273

Physical dimensions can be obtained this way:

var displayInformation = Windows.Graphics.Display.DisplayInformation.getForCurrentView();
var scale = displayInformation.resolutionScale;
var height = Math.ceil(window.outerHeight * scale / 100);
var width = Math.ceil(window.outerWidth * scale / 100);

var physicalWidth = width / displayInformation.rawDpiX; // in inches
var physicalHeight = height / displayInformation.rawDpiY; // in inches
var physicalSize = Math.floor(Math.sqrt(Math.pow(physicalWidth, 2) + Math.pow(physicalHeight, 2)) * 10) / 10; // in inches

I have tried this on several screen sizes and the physicalSize will be accurate in most cases, sometimes with 0.1" error.

I hope it can be helpful.

Upvotes: 1

Dominic Hopton
Dominic Hopton

Reputation: 7292

To get the size, you need:

window.outerWidth
window.outerHeight

This will return the logical size with scale factors already applied.

Note that you also want to listen for View State Changes, and when you enter/leave snapped, fill, full modes to make sure that your UI adjusts to the new window sizes.

Specifically, you need to either use CSS media query matching:

var snappedNotification = matchMedia("all and (-ms-view-state: snapped)");
snappedNotification.addEventListener(mySnappedFunction);

Or listen for window.resize, and use the current view state to look at the current view:

var currentViewState = Windows.UI.ViewManagement.ApplicationView.value;

http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.viewmanagement.applicationviewstate.aspx

Upvotes: 3

Leon Lucardie
Leon Lucardie

Reputation: 9730

The following JavaScript code should work:

var height = $('#bodyTag').outerHeight(true);

var width = $('#bodyTag').outerWidth(true);

You can also use the resolutionScale enum if you want to size your canvas based on scale:

var resolutionScale = Windows.Graphics.Display.DisplayProperties.resolutionScale;

Upvotes: 0

Related Questions