gpt4 book ai didi

javascript - Canvas 在javascript中为空错误

转载 作者:太空狗 更新时间:2023-10-29 14:41:22 25 4
gpt4 key购买 nike

我有这段代码:

<!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 is null 错误

最佳答案

下面这行代码有两个问题:

var canvas = document.getElementById("canvas"),
  1. 它在 Canvas 元素被解析并添加到 DOM 之前运行。
  2. 它使用了错误的 ID。

将其更改为:

var canvas = document.getElementById("Mycanvas"),

...并移动整个<script> block 到主体的末尾,就在 </body> 之前.

关于javascript - Canvas 在javascript中为空错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17881624/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com