0
캔버스 객체에 작은 사각형을 그려서 왼쪽 또는 오른쪽으로 움직이는 데 사용하는 자바 스크립트 코드가 있는데이 오류가 나타납니다. 그리고 나는 이유를 모른다.오류 : 잡히지 않은 TypeError : this.draw가 함수가 아닙니다.
function Walker(canvas, ctx) {
console.log("Received canvas with (" + canvas.width + ", " + canvas.height + ")");
this.x = Math.floor((Math.random() * canvas.width) + 1);
this.y = Math.floor((Math.random() * canvas.height) + 1);
this.canvas = canvas;
this.ctx = ctx;
this.draw = function(x = this.x, y = this.y) {
console.log("Drawing at (" + this.x + ", " + this.y + ")");
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.ctx.beginPath();
this.ctx.rect(this.x, this.y, 5, 5);
this.ctx.fillStyle = "#000000";
this.ctx.fill();
this.ctx.closePath();
};
this.walk = function() {
left_or_right = Math.floor(Math.random() * 2);
if(left_or_right === 0) {
console.log("Moving right");
this.x += 1;
}
else {
console.log("Moving left");
this.x -= 1;
}
this.draw(this.x, this.y);
};
}
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var w = new Walker(canvas, ctx);
w.draw();
setInterval(w.walk, 10000);
이 내 .html 파일입니다 :
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Gamedev Canvas Workshop</title>
<link rel="stylesheet" type="text/css" href="../css/style.css">
</head>
<body>
<canvas id="myCanvas" width="480" height="320"></canvas>
<script src="../scripts/walk.js" type="text/javascript"></script>
</body>
</html>
이 코드에 어떤 문제가 있습니까?
-
2) 당신은
bind
기능을 사용할 수 있습니다. –감사합니다. 당신은 생명의 은인입니다! –