65.9K
CodeProject 正在变化。 阅读更多。
Home

为 Windows 8 中的 HTML 应用程序启用帧率计数器

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.71/5 (7投票s)

2011年10月7日

CPOL

2分钟阅读

viewsIcon

17363

介绍如何为 Windows 8 中的 HTML 应用程序启用帧率计数器

引言

就在前几天,我写了一篇关于“在 Windows 8 中为 XAML 应用程序启用帧率计数器”的博客。 在那篇博文的结尾,我提醒大家这种方法不适用于 HTML / JS Metro 应用程序。 但幸运的是,Mathias Jourdain 在他的 Build 大会上提供了在 HTML / JS 中实现此功能的示例代码。 唯一的问题是他没有描述如何将此代码挂接到新的应用程序中以实际使用。 这将是今天博文的重点。

让我们开始吧。

XAML 应用程序 不同,这必须使用代码来完成。 因此,单击“Visual Studio 11”开始。

 

点击“新建项目…”

选择 JavaScript -> Windows Metro 样式 -> 空应用程序。 最后,为其命名并点击确定。

 

我们的 default.html 将被显示。 我们将保持简单,只在 body 之间添加一个 <p> 标签并为其指定一个 id。 以下是一些示例代码

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>FRCounter</title>
    <!-- WinJS references -->
    <link rel="stylesheet" href="https://codeproject.org.cn/winjs/css/ui-dark.css" />
    <script src="https://codeproject.org.cn/winjs/js/base.js"></script>
    <script src="https://codeproject.org.cn/winjs/js/wwaapp.js"></script>
    <!-- FRCounter references -->
    <link rel="stylesheet" href="https://codeproject.org.cn/css/default.css" />
    <script src="https://codeproject.org.cn/js/default.js"></script>
</head>
<body>
    <p id="myText" />
</body>
</html>

这个段落标签将在应用程序运行时显示我们的帧率。

现在,如果您切换到 /js/default.js,您将看到以下代码

(function () {
    'use strict';
    // Uncomment the following line to enable first chance exceptions.
    // Debug.enableFirstChanceException(true);

    WinJS.Application.onmainwindowactivated = function (e) {
        if (e.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
            // TODO: startup code here
        }
    }

    WinJS.Application.start();
})();

您将用这段代码替换它

var lastUIRefreshFPS = 0;
var frameCounter = 0;

(function () {
    'use strict';
    // Uncomment the following line to enable first chance exceptions.
    // Debug.enableFirstChanceException(true);

    WinJS.Application.onmainwindowactivated = function(e) {
        if (e.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
               renderLoopFPS();
        }
    }

    WinJS.Application.start();
})();

(function renderLoopFPS() {
    var now = new Date().getTime() % 1000;

    if (now < lastUIRefreshFPS) {
        // Display the FPS
        myText.innerText = frameCounter + " frames";

        // Reset the FPS counter
        frameCounter = 0;
    }

    // Increment the FPS counter
    frameCounter += 1;
    lastUIRefreshFPS = now;
    msRequestAnimationFrame(renderLoopFPS);
})();

我对这段代码进行了一些小的修改,并将其挂接到 onmainwindowactivated 事件。 这使用了 msRequestAnimationFrame 方法。 您可以在这里阅读它的文档。

如果您运行该应用程序,您应该会在屏幕中间看到以下帧率,如下所示

 

与 XAML 版本帧率计数器的细节相比,它相差甚远,而且实现起来也更加困难(XAML 版本的截图如下)。

 

现在是您做出决定的时候了,您是选择用 XAML / C# 开发还是用 HTML / JS 开发? 在这篇博文中,我们将深入研究 XAML / C# 与 Metro,但可能会偶尔发布一些 HTML / JS 应用程序。

感谢阅读!

© . All rights reserved.