0

The shape I put on the canvas is always in some way warped. I'm not sure if it's my canvas dimensions or just bad code. (although if it was bad code, probably would have fixed it by now). Here is my code:

<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>

And here is the CSS for the canvas:

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

I've tried changing some of the dimensions, it still comes out this way. Browser I am testing is Chrome.

C12
  • 79
  • 1
  • 2
  • 7
  • 1
    "don't use css to resize your canvas" use this as a search term, you'll find your solution. – Kaiido Jul 22 '16 at 00:58

1 Answers1

2

You're setting the width and height of the canvas to 1000px, but then you set the css width and height to 100%.

The canvas will be still 1000*1000 pixels, but the CSS will scale the content to match the aspect ratio of the window.

Imagine the canvas as an image. If you resize an image, then it will be distorted.

Simply remove the CSS styles.

Bálint
  • 4,009
  • 2
  • 16
  • 27