madhu kumar
madhu kumar

Reputation: 810

Why the variable declaration is showing error in Windows 8 application?

I am working on windows 8 Winjs application. This is the code where I am declaring variables in javascript. Why the 2nd line is showing error "0x800a138f - JavaScript runtime error: Unable to get property 'getContext' of undefined or null reference." Is the way of declaring canvas.getcontext is wrong? The same code works fine in desktop chrome but it's not working in Simulator.

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

Upvotes: 0

Views: 643

Answers (2)

Sushil
Sushil

Reputation: 5535

access your dom elements after the page is loaded. that can be done in the page.ready event handler.

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>

Upvotes: 1

Konstantin Dinev
Konstantin Dinev

Reputation: 34905

There is no element with id canvas loaded. Your var canvas is null after the assignment. Make sure you are performing all this inside you app.ready callback when the DOM is ready.

app.onready = function (args) {
    var canvas = document.getElementById('canvas'),
        context = canvas.getContext('2d'),
        controls = document.getElementById('controls'),
        animateButton = document.getElementById('animateButton');
}

Upvotes: 0

Related Questions