2016-07-22 73 views
0

我放在画布上的形状总是以某种方式扭曲。我不确定这是我的画布尺寸还是错误的代码。 (尽管如果它是不好的代码,现在可能会修复它)。这里是我的代码:画布fillRect高度和宽度总是倾斜/扭曲

<script type = "text/javascript"> 
var game = document.getElementById("game"); 
//To keep the shapes from coming out with low resolution/a fuzzy look 
game.height = 1000; 
game.width = 1000; 
var context = game.getContext("2d"); 
var gamePieces = [] 
function gamePiece(width, height, color, x, y){ 
    this.width = width; 
    this.height = height; 
    this.x = x; 
    this.y = y; 
    this.update = function(){ 
     context.fillStyle = color; 
     context.fillRect(this.x, this.y, this.height, this.width); 
    } 
    this.move = function(distancex, distancey, leftOrRight, upOrDown){ 
     if(leftOrRight.toLowerCase() == "left"){ 
      this.x = this.x - distancex 
     } else if(leftOrRight.toLowerCase() == "right"){ 
      this.x = this.x + distancex; 
     } 
     if(upOrDown.toLowerCase() == "up"){ 
      this.y = this.y - distancey; 
     } else if(upOrDown.toLowerCase() == "down"){ 
      this.y = this.y + distancey 
     } 
    } 
    gamePieces[gamePieces.length] = this 
    context.fillStyle = color; 
    context.fillRect(this.x, this.y, this.height, this.width); 
} 
function update(){ 
    context.clearRect(0, 0, game.width, game.height); 
    for(var i = 0; i < gamePieces.length; i++){ 
     gamePieces[i].update(); 
    } 
} 
setInterval(update, 1); 
var p1 = new gamePiece(100, 100, "blue", 0, 0); 

</script> 

,这里是在画布的CSS:

#game { 
    height: 100%; 
    width: 100%; 
} 

我试着改变一些尺寸,但它仍然出来这种方式。我正在测试的浏览器是Chrome。

+1

“不要使用css来调整您的画布大小”将此用作搜索词,您会找到解决方案。 – Kaiido

回答

1

您正在将画布的宽度和高度设置为1000px,但将css的宽度和高度设置为100%。

画布仍然是1000 * 1000像素,但CSS会缩放内容以匹配窗口的纵横比。

想象一下画布是一个图像。如果您调整图像大小,那么它将会失真。

只需删除CSS样式。