为什么updatePosition不读取Square中的fall函数?它假设是从顶部掉下一块,但没有任何事情发生。似乎无法解决问题。它与在另一个函数内调用函数调用有关。
var WIDTH = 300,
HEIGHT = 400,
c = document.getElementById('canvas'),
ctx = c.getContext('2d');
setInterval(function () {
clearCanvas();
updatePosition();
drawOnCanvas();
}, 1000 / 50);
var clearCanvas = function () {
ctx.fillStyle = 'White';
ctx.beginPath();
ctx.rect(0, 0, WIDTH, HEIGHT);
ctx.closePath();
ctx.fill();
}
var drawLine = function () {
ctx.beginPath();
ctx.moveTo(200, 0);
ctx.lineTo(200, 400);
ctx.stroke();
}
var updatePosition = function () {
Square.fall();
}
var drawOnCanvas = function () {
drawLine();
Square.draw();
}
var speedLevels = [20, 16, 12, 10, 8],
currSpeed = speedLevels[0];
var Square = function (speed) {
var self = this;
self.color = "Black";
self.vPosition = 0;
self.hPosition = 4;
self.speed = speed;
self.temp = 0;
self.fall = function () {
if (self.temp == self.speed) {
self.vPosition++;
self.temp = 0;
}
self.temp++;
}
self.draw = function () {
console.log(self.vPosition * squareLength);
ctx.fillStyle = self.color;
ctx.fillRect(self.hPosition * squareLength, self.vPosition * squareLength, squareLength, squareLength);
}
return self;
}
答案 0 :(得分:0)
首先,您正在调用Square.fall()
和Square.draw()
,好像Square
是对象的实例 - 它不是,因为您没有在任何地方Square = new ...
。
其次,您正在使用未在任何地方定义的变量squareLength
。
var _Square = function(speed) {
var self = this;
self.color = "Black";
self.vPosition = 0;
self.hPosition = 4;
self.speed = speed;
self.temp = 0;
squareLength = 1;
self.fall = function() {
if (self.temp == self.speed) {
self.vPosition++;
self.temp = 0;
}
self.temp++;
}
self.draw = function() {
console.log(self.vPosition * squareLength);
ctx.fillStyle = self.color;
ctx.fillRect(self.hPosition * squareLength, self.vPosition * squareLength, squareLength, squareLength);
}
return self;
}
var WIDTH = 300,
HEIGHT = 400,
c = document.getElementById('canvas'),
ctx = c.getContext('2d');
var Square = new _Square(10);
setInterval(function() {
clearCanvas();
updatePosition();
drawOnCanvas();
}, 1000 / 50);
var clearCanvas = function() {
ctx.fillStyle = 'White';
ctx.beginPath();
ctx.rect(0, 0, WIDTH, HEIGHT);
ctx.closePath();
ctx.fill();
}
var drawLine = function() {
ctx.beginPath();
ctx.moveTo(200, 0);
ctx.lineTo(200, 400);
ctx.stroke();
}
var updatePosition = function() {
Square.fall();
}
var drawOnCanvas = function() {
drawLine();
Square.draw();
}
var speedLevels = [20, 16, 12, 10, 8],
currSpeed = speedLevels[0];
canvas {
border: 1px solid red;
width: 300px;
height: 400px;
}
<canvas id='canvas'></canvas>