0

当我尝试运行以下代码时,我刚刚在 Windows 8 上安装了 vs 2012,并为 Windows 8 创建了一个示例 javascript 应用程序

<!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>

它给出了以下例外

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.
4

2 回答 2

2

改变

var c = $("myCanvas");

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

接着

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

您可以使用 jQuery 来获取带有 $('#myCanvas').get(0) 的元素,以访问实际的 HTML 元素对象。不过,标准的文档 api 在这里也能正常工作。

http://diveintohtml5.info/canvas.html

更新:

将代码包装在准备好的文档中

$(function(){
    //code here
});
于 2012-11-27T18:06:00.587 回答
-1

改变

var c = $("myCanvas");

var c = $("#myCanvas");
于 2015-06-19T16:34:00.930 回答