0
我有這個JavaScript代碼,我用畫在畫布對象上的一個小方塊,並使其向左或向右移動,但我收到此錯誤我不知道爲什麼。錯誤:未捕獲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>
什麼是錯的代碼?
我已經添加了我的.html文件。 –
謝謝你,你是一個拯救生命的人! –