Exception while trying to get context of a canvas in windows 8 app

0

I am just installed vs 2012 on windows 8 and create a sample javascript app for windows 8 now when I try to run following code

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>App1</title>

<!-- WinJS references -->
<link href="//Microsoft.WinJS.1.0/css/ui-dark.css" rel="stylesheet" />
<script src="//Microsoft.WinJS.1.0/js/base.js"></script>
<script src="//Microsoft.WinJS.1.0/js/ui.js"></script>

<!-- App1 references -->
<script src="js/jquery-1.5.1.min.js"></script>
<link href="/css/default.css" rel="stylesheet" />

<script src="/js/default.js"></script>
  <script type="text/javascript" >
      var c = $("myCanvas");
      var ctx = c.getContext("2d");
      var grd = ctx.createLinearGradient(0, 0, 175, 50);
      grd.addColorStop(0, "#000000");
      grd.addColorStop(1, "#00FF00");
      ctx.fillStyle = grd;
      ctx.fillRect(0, 0, 150, 75);
</script>
</head>
<body>
<form>
    <input type="url" />
    <input type="submit" value="ok" />
    <canvas id="myCanvas" width="200" height="200">
        Your browser doesn't support canvas
    </canvas>
</form>

its giving the following exception

Unhandled exception at line 19, column 11 in ms-appx://ce20ab64-b644-451a-a60f-cafdc7afb4f9/default.html

0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'getContext'

If there is a handler for this exception, the program may be safely continued.
javascript
canvas
windows-8
html5-canvas
asked on Stack Overflow Nov 27, 2012 by Smartboy

2 Answers

2

Change

var c = $("myCanvas");

to

var c = document.getElementById("myCanvas");

and then

var ctx = c.getContext("2d");

You could use jQuery to get the element with $('#myCanvas').get(0) to get access to the actual HTML element object. The standard docuemnt api works just as well here though.

http://diveintohtml5.info/canvas.html

Update:

Wrap code in document ready with

$(function(){
    //code here
});
answered on Stack Overflow Nov 27, 2012 by arhea • edited Nov 27, 2012 by arhea
-1

Change

var c = $("myCanvas");

to

var c = $("#myCanvas");
answered on Stack Overflow Jun 19, 2015 by bhargav chava • edited Jun 19, 2015 by josliber

User contributions licensed under CC BY-SA 3.0