gpt4 book ai didi

javascript - Canvas 不在 JS/HTML 中绘制

转载 作者:太空宇宙 更新时间:2023-11-04 08:58:13 25 4
gpt4 key购买 nike

我收到此错误:“无法读取 null 的属性‘getContext’”我用这个问题查找了其他人,他们都在创建 HTML div 之前运行了 JS,但对我来说并非如此。我已将 JSFiddle 与我的代码链接起来,但效果不佳,因为我有固定元素。有人请帮忙,我不知道发生了什么事。JSFIDDLE:https://jsfiddle.net/alec935/Ln7yghbx/1/

HTML:

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<head>
<title>Snake</title>
<link rel="stylesheet" href="snake.css">
<script type="text/javascript" src="jquery-3.2.0.min.js"></script>
</head>
<body>
<div id="game">
<div id="play">
<canvas id="playBoard"></canvas>
<script src="snake.js"></script>
</div>
<div id="credits"><h1><i>Snake Game</i>, designed by Alec xxxxx</h1></div>
<div id="info"></div>
</div>
</body>
</html>

CSS:

@keyframes pulsate {
0% {color:white}
50% {color:black;}
100% {color:white}
}

body {
background-image:url(images/snaxe.jpg);
background: fill;
}

#game{
width:1450px;
height:800px;
background-color:black;
margin: 0 auto;
position:relative;
}

#credits {
color: white;
font-size: 19px;
text-shadow: rgb(255, 255, 255) 0px -1px 4px, rgb(255, 255, 0) 0px -2px 10px, rgb(255, 128, 0) 0px -10px 20px, rgb(255, 0, 0) 0px -18px 40px;
animation: pulsate 4s infinite;
}

#play{
width:720px;
height:720px;
background-color:red;
z-index:1;
}

#playBoard {
width:720px;
height:720px;
z-index:0;
}

#info{
position:fixed;
top:8px;
right:115px;
width:730px;
height:800px;
background-color:white;
z-index: 1;
}

JavaScript:

$(function() {
var snakeX, snakeY;
var fruitX, fruitY;
var gameOver = true;
var direction = 0; //0 = null, 1 = left, 2 = right, 3 = up, 4 = down

function Draw() {
var canvas = document.getElementById("playBoard");
var ctx = canvas.getContext("2d");

//Snake
ctx.beginPath();
ctx.lineWidth="5";
ctx.strokeStyle="green";
ctx.fillRect(385,385,50,50);

}


function Setup() {
gameOver = false;
Draw();
}

window.onload = Setup;
});

编辑:我的 Canvas 元素中有错字。这已被修复。但是,问题仍然存在。

最佳答案

仔细检查您的 HTML。您的 ID 放错地方了。

<canvas>id="playBoard"</canvas>

应该是

<canvas id="playBoard"></canvas>

关于javascript - Canvas 不在 JS/HTML 中绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42962482/

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