我正在尝试使用本教程:http://html5gamedev.samlancashire.com/making-a-simple-html5-canvas-game-part-1-moving-a-sprite/
我已经检查了我的代码,它与教程指示的完全相同(这里是:http://pastebin.com/1JsU28cx),但是当我运行控制台时给出了这个错误:“未捕获的TypeError:无法读取属性” getContext'为null“
错误发生在var ctx = canvas.getContext('2d'); 我看过几个类似的问题,但他们没有帮助......
我不知道如何解决这个问题......
谢谢!
编辑:我忘了在html
中识别画布答案 0 :(得分:2)
我可以从您的javascript唯一的粘贴码中确定,您要么没有CREATE TABLE IF NOT EXISTS `Category` (
`category_id` int(20) NOT NULL default '',
`name` varchar(100) NOT NULL,
`description` varchar(200) NOT NULL,
`sub_category_id` int(20) NULL,
PRIMARY KEY (category_id, name),
FOREIGN KEY Category(sub_category_id) REFERENCES Category(category_id) ON DELETE CASCADE
);
-- --------------------------------------------------------
CREATE TABLE IF NOT EXISTS `Owner` (
`password` varchar(100) NOT NULL default '',
`account_name` varchar(100) NOT NULL default '',
PRIMARY KEY (password, account_name)
);
,要么其ID不是<canvas>
。请务必将ID更改为"canvas"
,否则"canvas"
将返回document.getElementById
:
null
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
canvas.width = 800;
canvas.height = 600;
var mySprite = {
x: 200,
y: 200,
width: 50,
height: 50,
speed: 200,
color: '#c00'
};
var keysDown = {};
window.addEventListener('keydown', function(e) {
keysDown[e.keyCode] = true;
});
window.addEventListener('keyup', function(e) {
delete keysDown[e.keyCode];
});
function update(mod) {
if (37 in keysDown) {
mySprite.x -= mySprite.speed * mod;
}
if (38 in keysDown) {
mySprite.y -= mySprite.speed * mod;
}
if (39 in keysDown) {
mySprite.x += mySprite.speed * mod;
}
if (40 in keysDown) {
mySprite.y += mySprite.speed * mod;
}
}
function render() {
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = mySprite.color;
ctx.fillRect(mySprite.x, mySprite.y, mySprite.width, mySprite.height);
}
function run() {
update((Date.now() - time) / 1000);
render();
time = Date.now();
}
var time = Date.now();
setInterval(run, 10);
window.addEventListener("keydown", function(e) {
// space and arrow keys
if([32, 37, 38, 39, 40].indexOf(e.keyCode) > -1) {
e.preventDefault();
}
}, false);