HTML5 Canvas getContext问题

时间:2014-11-23 03:08:28

标签: jquery html5 html5-canvas

我正在尝试创建一个带有图像的2D画布但是我一直收到关于getContext的以下错误......

//localhost :50400/Scripts/game.js第9行第1行未处理的异常 0x800a138f - JavaScript运行时错误:无法获取未定义或空引用的属性“getContext”

我不确定从哪里开始......

HTML

<!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
    </head>
    <body>
        <canvas id="gameCnavas" width="800" height="600"></canvas>
        <script src="Scripts/jquery-2.1.1.js"></script>
        <script src="Scripts/game.js"></script>
    </body>
    </html>

JS

/// <reference path="jquery-2.1.1.js" />

var canvasWidth = 800;
var canvasHeight = 600;

$('gameCanvas').attr('width', canvasWidth);
$('gameCanvas').attr('height', canvasHeight);

var canvas = $('#gameCanvas')[0].getContext('2d');

canvas.strokeRect(0, 0, canvasWidth, canvasHeight);

var image = new Image();
image.src = "ship.png";

$(image).load(function () {
    canvas.drawImage(image, (canvasWidth * .5) - (image.width * .5),
        (canvasHeight * .5) - (image.height * .5));
});

2 个答案:

答案 0 :(得分:1)

你在代码中犯了错误。

在您的HTML代码中,您将id编写为“gameCnavas”:

<canvas id="gameCnavas" width="800" height="600"></canvas>

但是你在脚本中引用的id是“gameCanvas”:

var canvas = $('#gameCanvas')[0].getContext('2d');

换句话说,Id不匹配,这就是你得到Null引用错误的原因。

答案 1 :(得分:1)

从...中更改画布对象ID

<canvas id="gameCnavas" width="800" height="600"></canvas>

为...

<canvas id="gameCanvas" width="800" height="600"></canvas>