Windows 8开发人员中心的Windows 8 HTML5 / JavaScript Canvas教程不起作用

时间:2012-12-01 23:37:44

标签: windows-8

我正在尝试在Windows 8开发人员中心完成本教程:http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh452750.aspx

但还没有超越第一步。在我的HTML5文件中,我有:

<canvas id="can1" width="500" height="500"></canvas>

在我的JavaScript文件中,我有:

var myCanvas = document.getElementById("can1");
var myContext = myCanvas.getContext("2d");

我正在使用Visual Studio Express 2012 for Windows 8.我收到以下错误:“0x800a138f - JavaScript运行时错误:无法获取未定义或空引用的属性'getContext'”

这正是教程所要做的。为什么我收到错误?

1 个答案:

答案 0 :(得分:3)

如果您正在使用空白模板(如评论中所述),那么将建议的演示代码放在onactivated事件中应该有效。以下内容应显示黑框左上角到右下角的白线。

default.html中的

<body>
    <p>Content goes here</p>
    <canvas id="can1" width="500" height="500"></canvas>
</body>

在default.js中,在app.onactivated方法中:

app.onactivated = function (args) {
    if (args.detail.kind === activation.ActivationKind.launch) {
        if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
            // TODO: This application has been newly launched. Initialize
            // your application here.
        } else {
            // TODO: This application has been reactivated from suspension.
            // Restore application state here.
        }

        var myCanvas = document.getElementById("can1");
        var myContext = myCanvas.getContext("2d");

        myContext.fillStyle = '#000';
        myContext.strokeStyle = '#fff';
        myContext.fillRect(0, 0, 500, 500);
        myContext.lineWidth = 3;
        myContext.fill();

        myContext.moveTo(0, 0);
        myContext.lineTo(500, 500);
        myContext.stroke();

        args.setPromise(WinJS.UI.processAll());
    }
};