0

我正在开发 Windows 8 Winjs 应用程序。这是我在 javascript 中声明变量的代码。为什么第二行显示错误“0x800a138f - JavaScript 运行时错误:无法获取未定义或空引用的属性 'getContext'。” 是不是声明canvas.getcontext的方式不对?相同的代码在桌面 chrome 中运行良好,但在模拟器中不起作用。

var canvas = document.getElementById('canvas'),
        context = canvas.getContext('2d'),
        controls = document.getElementById('controls'),
        animateButton = document.getElementById('animateButton');
4

2 回答 2

1

加载页面后访问您的 dom 元素。这可以在 page.ready 事件处理程序中完成。

page.js:
WinJS.UI.Pages.define('/pages/mypage/page.html', 
    {
        ready: function onready(element, options)
        {
            // all dom elements with id will have the respective variables available here.
            // need not create variable for canvas.
            var context = canvas.getContext('2d');
        }
    });

page.html:

<html>
<head>
    <title></title>
    <link href="/pages/mypage/mypage.css" rel="stylesheet" />
    <script src="/pages/mypage/mypage.js" type="text/javascript"></script>
</head>
<body>
    <div class="mypage fragment">
        <header role="banner">
            <button class="win-backbutton" aria-label="Back" disabled type="button"></button>
            <h1 class="titlearea win-type-ellipsis">
                <span class="pagetitle">My Page</span>
            </h1>
        </header>
        <section aria-label="Main content" role="main">
            <canvas id="canvas">
            </canvas>
        </section>
    </div>
</body>

于 2013-06-12T13:30:14.830 回答
0

没有加载 id 画布的元素。你var canvasnull在分配之后。确保在准备好后在app.ready回调中执行所有这些操作。DOM

app.onready = function (args) {
    var canvas = document.getElementById('canvas'),
        context = canvas.getContext('2d'),
        controls = document.getElementById('controls'),
        animateButton = document.getElementById('animateButton');
}
于 2013-06-12T12:47:17.983 回答