简斯 |getContext('2d')的问题



我最近使用canvas.getContext('2d'(方法遇到了一些问题。我试图在全局范围中将其声明为let,但声明为空,并在const中初始化它。但我不能把它称为超出了这个常数。我记得这在一段时间前起了作用,有什么变化吗?或者我的代码有什么问题?

谢谢你的回答!

(() => {
let request;
let canvas;
let ctx;
const start = document.getElementById("start");
const menu = document.getElementById("start-menu");
const init = () => {
canvas = document.createElement('canvas');
canvas.width = window.screen.availWidth - (window.outerWidth - window.innerWidth + 20);
canvas.height = window.screen.availHeight - (window.outerHeight - window.innerHeight + 20);
canvas.id = "animation-panel";
ctx = canvas.getContext('2d');


document.body.appendChild(canvas);
}
const animate = () => {
request = requestAnimationFrame(animate);
draw();
}  
const draw = () => {
var playerPosX = 50;
var playerPosY = 50;

//i want to call the ctx here

}
init();
start.addEventListener("click", () => {
menu.style.display = "none";
animate();
})
})()
* {
font-family: Arial, Helvetica, sans-serif;
}
body {
background-color: white;
overflow: hidden;
}
#animation-panel {
border: 2px solid black;
}
#start-menu {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
border: 3px solid black;
padding: 50px 150px 50px 150px;
background-color: #A758DB;
display: true;
}
#high-score {
text-align: center;
font-size: 18px;
}
#start {
letter-spacing: 5px;
font-size: 60px; 
background-color: #A758DB;
border: 3px solid black;
color: black;
text-decoration: none;
}
#start:hover {
border: 3px solid white;
color: white;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<div id = "start-menu">
<button id="start">Start</button>
<p id ="high-score">Your High-Score: 0</p>
<script src="script.js"></script>
</div>
</body>
</html>

初始化后不能更改const值(不包括更改对象属性(。在您的示例中,一切都很好,ctx可以在您"想要调用ctx"的地方使用。如果我误解了这个问题,我很抱歉。

const a = 1;
a = 2; // Uncaught TypeError: Assignment to constant variable.

更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const.

所以我的问题是Visual Studio代码。Intellisense只是没有显示我的代码已经完成。我可能会切换到Web Storm进行Web开发。

最新更新