2016-07-22 42 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樣式。