canvas 中未将变量设置为矩形
Not setting variable to rectangle in canvas
我试图通过将 1 添加到矩形的 x/y 位置来在您单击按钮时移动矩形,但速度变量一直显示未定义。
// . . . //
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function(){
ctx = gameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.newPos = function(){
this.x += this.speedX;
this.y += this.speedY;
}
}
function updateGameArea(){// Update games at 50fps
gameArea.clear();
bluePiece.newPos();
bluePiece.update();
}
function moveUp(piece){
piece.speedY -= 1;
console.log("UP "+piece+" S:"+piece.speedY);
}
function moveDown(piece){
piece.speedY += 1;
console.log("DOWN "+piece+" S:"+piece.speedY);
}
function moveLeft(piece){
piece.speedX -= 1;
console.log("LEFT "+piece+" S:"+piece.speedX);
}
function moveRight(piece){
piece.speedY += 1;
console.log("RIGHT "+piece+" S:"+piece.speedX);
}
注意:如果您想查看完整代码以更好地理解发生了什么,请转至 here 并按 ctrl+U 查看完整代码 .
你将一个字符串传递给函数,然后访问 String 的 属性,这肯定是未定义的。
尝试 console.log(typeof piece);
我试图通过将 1 添加到矩形的 x/y 位置来在您单击按钮时移动矩形,但速度变量一直显示未定义。
// . . . //
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function(){
ctx = gameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.newPos = function(){
this.x += this.speedX;
this.y += this.speedY;
}
}
function updateGameArea(){// Update games at 50fps
gameArea.clear();
bluePiece.newPos();
bluePiece.update();
}
function moveUp(piece){
piece.speedY -= 1;
console.log("UP "+piece+" S:"+piece.speedY);
}
function moveDown(piece){
piece.speedY += 1;
console.log("DOWN "+piece+" S:"+piece.speedY);
}
function moveLeft(piece){
piece.speedX -= 1;
console.log("LEFT "+piece+" S:"+piece.speedX);
}
function moveRight(piece){
piece.speedY += 1;
console.log("RIGHT "+piece+" S:"+piece.speedX);
}
注意:如果您想查看完整代码以更好地理解发生了什么,请转至 here 并按 ctrl+U 查看完整代码 .
你将一个字符串传递给函数,然后访问 String 的 属性,这肯定是未定义的。
尝试 console.log(typeof piece);