전역 변수 mouseX, mouseY를 함수 내부의 이벤트 리스너에 할당하려고합니다. 다른 함수에서 변수를 사용하려고하면 다시 정의되지 않습니다.함수에서 전역 변수가 정의되지 않았습니다.
할당 된 변수의 범위에는 문제가있을 수 있지만 알아낼 수는 없으므로 작성한 간단한 테스트 코드는 문제를 재현하지 않습니다.
이 문제의 원인은 무엇입니까?
자바 스크립트 :이 루프는 한 번만 실행중인 :
var mouseX, mouseY;
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var bars = [];
for(var i = 0; i < 30; i++)
bars[i] = new Bar(ctx, 100+i*10, canvas.height, 5, 150);
for(var i = 0; i < bars.length; i++){
bars[i].checkMouse();
bars[i].display();
}
function Bar(ct, x, y, w, h){
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.y -= this.h;
this.display = function() {
ct.rect(this.x, this.y, this.w, this.h);
ct.fill();
}
this.checkMouse = function() {
//if(mouseX >= this.x && mouseX <= this.x + this.w){
//this.y = mouseY; this.h = height-mouseY;
console.log(mouseX); //////mouseX is undefined?
//}
}
}
function getMouse(event) {
mouseX = event.offsetX;
mouseY = event.offsetY;
var coords = "mouseX: " + mouseX + ", mouseY: " + mouseY;
document.getElementById('display').innerHTML = coords;
}
HTML :
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
canvas{
background-color: #e6e6e6;
position:relative;
}
</style>
</head>
<body>
<div id="display"> </div>
<canvas onmousemove="getMouse(event)" id="myCanvas" width="500" height="200">
<script src="myscript.js"></script>
</body>
</html>
this와 같이 mouseX를 전달 this.checkMouse = function (mouseX) {// – Bugfixer
이것은 OP의 질문에 대한 답변이 아닙니다. –
'getMouse'를 호출 할 때까지'mouseX'와'mouseY'를 설정하지 않고 이벤트가 실행되기 전에'bars [i] .checkMouse();'* 만 호출하면됩니다. – h2ooooooo