我正在使用Windows 8 Winjs应用程序。这是我在javascript中声明变量的代码。为什么第二行显示错误“0x800a138f - JavaScript运行时错误:无法获取未定义或空引用的属性'getContext'。”声明canvas.getcontext的方式是错误的吗?相同的代码在桌面chrome中工作正常,但它在Simulator中不起作用。
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
controls = document.getElementById('controls'),
animateButton = document.getElementById('animateButton');
答案 0 :(得分: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>
答案 1 :(得分:0)
没有加载id canvas的元素。作业完成后,var canvas
为null
。 app.ready
准备好后,请确保在DOM
回调内执行所有这些操作。
app.onready = function (args) {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
controls = document.getElementById('controls'),
animateButton = document.getElementById('animateButton');
}