javascript中Canvas为null错误
Canvas is null error in javascript
我有这个代码:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
canvas{border:#666 1px solid;}
</style>
<script type="text/javascript">
var canvas = document.getElementById("canvas"),
context = canvas.getContext("2d"),
playerimage = new Image(),
x = canvas.width / 2, //align to centre of the screen
y = canvas.height / 2, //same as above
speed = 5, //speed for the player to move at
width = 50, //width of the player
height = 50; //height of the player
function init() {
playerimage.src = "ninja.png"; //path to the image to use for the player
canvas.addEventListener("keypress", update);
}
function update(event) {
if (event.keyCode == 38) {
y -= speed; //going up
}
if (event.keyCode == 40) {
y += speed; //going down
}
if (event.keyCode == 37) {
x -= speed; //going left
}
if (event.keyCode == 39) {
x += speed; //going right
}
render();
}
function render() {
// context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(playerimage, x, y, width, height);
}
</script>
</head>
<body onload="init();">
<button onclick="init();">Draw</button>
<canvas id="Mycanvas" width="550" height="400"></canvas>
</body>
</html>
javascript控制台总是给我canvas为空错误
以下代码行存在两个问题:
var canvas = document.getElementById("canvas"),
- 它在画布元素被解析并添加到DOM之前运行
- 它使用了错误的ID
更改为:
var canvas = document.getElementById("Mycanvas"),
并将整个<script>
块移动到主体的末端,刚好在</body>
之前。
html中画布的id与中使用的id不匹配
var canvas=document.getElementById("canvas");
正确的HTML应该是:
<canvas id="canvas" width="550" height="400"></canvas>
这是因为你在头上对接了脚本标记,但它在末尾的body标记中。
相关文章:
- 开箱即用的Light Switch HTML应用程序在IE9中存在null错误
- 如何删除此JavaScript null错误
- 失败:切换弹出窗口时,条目中的null值:name=null错误
- TypeError: document.getElementById(..) 为 null - 错误消息
- 与正则表达式一起使用时无法读取属性长度 null 错误
- 未捕获的类型错误:无法设置属性'className'的null错误
- Jquery无法读取null错误的属性
- 无法读取属性'addEventListener'的null错误
- javascript中Canvas为null错误
- 无法设置null错误的innerHTML.尽管存在html ID
- JavaScript表单属性null错误
- 使用带有javascript的单选按钮..获取null错误
- 为什么我得到'无法读取属性样式为null ';错误
- JavaScript视频播放null错误
- Slick .js不能添加null错误
- 三.js:无法补间对象位置 var(获得 null 错误),但对象本身实际上是可用的
- Google Sheet Script在循环过程中出现Null错误
- 包含jquery时,$(document)为null错误
- JavaScript getElementById返回null错误
- 无法读取属性'addEventListener'的null错误,不确定原因