0

I have a canvas that is being used for a JavaScript game. When using jQuery or external CSS, the canvas sizes correctly, but the game graphics are larger than they should be (causing most of the graphics to not appear on screen).

When using inline CSS, I get no graphical problems. Although it does get the job done, I need to be able to re-size the canvas at any time.

When using jQuery, I grab the canvas's context AFTER sizing, hoping that would work, but it didn't. Can someone inform me on whats going on, or direct me to where I can learn more about managing the context of HTML canvas?

Here is my HTML code that includes no inline-css

HTML:

<!DOCTYPE html>
<html>

        <head>
                <script type = "text/javascript" src = "//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
                <script type = "text/javascript" src = "games/snake.js"></script>

                <link rel = "stylesheet" type = "text/css" href = "styles/home.css" />
        </head>

        <body>
                <div id = "navBar" class = "navAtt">
                        <div id = "firstButton" class = "navButton">Play Game</div> 
                </div>

                <div id = "mainView" class = "center">
                        <canvas id = "canvas" class = "center"></canvas>
                </div> 

                <script>
                        var firstButton = $("#firstButton");
                        var canvas = $("#canvas");

                        firstButton.click(function() {
                                /* This is where I was sizing with jQuery; no other size methods were used
                                        canvas.width(450);
                                        canvas.height(400);
                                */
                                var ctx = $("#canvas")[0].getContext("2d");
                                startSnakeGame(canvas.width(), canvas.height(), ctx);
                        });
                </script>
        </body>
</html>

CSS:

body {
        background-color: #66C2FF;
        margin: 0;
}

#navBar {
        border-bottom: 2px solid #2CABB4;
        position: fixed;
        width: 100%;
}

#mainView {
        padding-top: 100px;
        width: 1200px;
}

#canvas { /* This is how I'm affecting the size; This is blank when I try using jQuery */
        width: 450px;
        height: 400px;
}

.center {
        margin-left: auto;
        margin-right: auto;
}

.navAtt {
        background-color: #29A3A3;
        height: 40px;
        opacity: 0.7;
}

.navButton {
        padding: 10px 20px;
        float:left;
}

JavaScript (the game)

function startSnakeGame(w, h, ctx) {
    init();

    var cw = 10;
    var d;
    var food;
    var score;
    var cw = 10;
    var d;
    var food;
    var score;
    var snake_array; 

    function init() {
        d = "right"; 
        create_snake();
        create_food(); 
        score = 0;

        if(typeof game_loop != "undefined") clearInterval(game_loop);
        game_loop = setInterval(paint, 60);
    }

    function create_snake() {
        var length = 5; 
        snake_array = []; 
        for(var i = length-1; i>=0; i--) {
            snake_array.push({x: i, y:0});
        }
    }

    function create_food() {
        food = {
            x: Math.round(Math.random()*(w-cw)/cw), 
            y: Math.round(Math.random()*(h-cw)/cw), 
        };
    }

    function paint() {
        ctx.fillStyle = "white";
        ctx.fillRect(0, 0, w, h);
        ctx.strokeStyle = "black";
        ctx.strokeRect(0, 0, w, h);

        var nx = snake_array[0].x;
        var ny = snake_array[0].y;

        if(d == "right") nx++;
        else if(d == "left") nx--;
        else if(d == "up") ny--;
        else if(d == "down") ny++;

        if(nx == -1 || nx == w/cw || ny == -1 || ny == h/cw || check_collision(nx, ny, snake_array)) {
            init();
            return;
        }

        if(nx == food.x && ny == food.y) {
            var tail = {x: nx, y: ny};
            score++;
            create_food();
        } else {
            var tail = snake_array.pop(); 
            tail.x = nx; tail.y = ny;
        }

        snake_array.unshift(tail);

        for(var i = 0; i < snake_array.length; i++) {
            var c = snake_array[i];
            paint_cell(c.x, c.y);
        }

        paint_cell(food.x, food.y);
        var score_text = "Score: " + score;
        ctx.fillText(score_text, 5, h-5);
    }

    function paint_cell(x, y) {
        ctx.fillStyle = "blue";
        ctx.fillRect(x*cw, y*cw, cw, cw);
        ctx.strokeStyle = "white";
        ctx.strokeRect(x*cw, y*cw, cw, cw);
    }

    function check_collision(x, y, array) {
        for(var i = 0; i < array.length; i++) {
            if(array[i].x == x && array[i].y == y)
             return true;
        }
        return false;
    }

    $(document).keydown(function(e) {
        var key = e.which;
        if(key == "37" && d != "right") d = "left";
        else if(key == "38" && d != "down") d = "up";
        else if(key == "39" && d != "left") d = "right";
        else if(key == "40" && d != "up") d = "down";
    })
}
Vince
  • 14,470
  • 7
  • 39
  • 84

3 Answers3

1

Your canvas is like an image, if you scale it with css the graphics will scale up. Use javascript to set the with and height of canvas.

var canvas = document.getElementsByTagName('canvas')[0];
canvas.width  = 450;
canvas.height = 450;

and this is a duplicate btw. Canvas width and height in HTML5

Community
  • 1
  • 1
Spoeken
  • 2,549
  • 2
  • 28
  • 40
0

For canvas the attributes width and height are not optional. Probably it's sizing to the "default" values.

http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html

'The width attribute defaults to 300, and the height attribute defaults to 150.'

<canvas id = "canvas" class = "center" width="450" height="400"></canvas>
miguel-svq
  • 2,136
  • 9
  • 11
0

I agree with Spoeken, it would be you can use html or javascript to change the size easily any time.

 <canvas id="canvas" class="canvas" width="500px" height="450px" style= css stuff here> </canvas>

I find it much easier to edit and create canvases this way.

asdfasdf
  • 5
  • 6