Cato Yeung
Cato Yeung

Reputation: 701

html5 canvas drawing position not correct

I am currently writing a simple snake game.
http://jsfiddle.net/jhGq4/3/
I started with drawing the grid for the background

function fill_grid() {
    ctx.beginPath();
    var row_no = w/cw;
    var col_no = h/cw;
    for (var i=0;i<row_no;i++)
    {
        for (var j=0;j<col_no;j++)
        {
            ctx.rect(i*cw, j*cw, (i+1)*cw, (j+1)*cw);
            ctx.fillStyle = 'black';
            ctx.fill();
            ctx.lineWidth = 1;
            ctx.strokeStyle = '#135d80';
            ctx.stroke();
        }
    }

}

It works great but when i paint the snake, the position gets wrong and the length is doubled. I tried to console.log the x position of my snake but they are correct.

function paint_cell(x, y)
{
    console.log(x*cw);
    console.log((x+1)*cw);
    ctx.fillStyle = '#fff799';
    ctx.fillRect(x*cw, y*cw, (x+1)*cw, (y+1)*cw);
    ctx.lineWidth = 1;
    ctx.strokeStyle = '#135d80';
    ctx.strokeRect(x*cw, y*cw, (x+1)*cw, (y+1)*cw);
}

***Because someone wants to learn how to make a snake game, this is my final solution for this game. http://jsfiddle.net/wd9z9/
You can also visit my site to play:

use WSAD to play. http://www.catoyeung.com/snake2/single.php :D

Upvotes: 3

Views: 370

Answers (1)

boisvert
boisvert

Reputation: 3729

I tested this alternative init function:

function init()
{
        fill_grid();
        // create_snake1();
        // paint_snake1();
        paint_cell(5, 5)
}

Which paints a square starting at coords (5,5), but of size 6x6.

I believe you are misusing the fillRect() method. Use

        ctx.fillRect(x*cw, y*cw, cw, cw);

Instead of

        ctx.fillRect(x*cw, y*cw, (x+1)*cw, (y+1)*cw);

the same probably applies to strokeRect.

Incidentally, I was looking at your grid-fill function. You fill i*j adjacent squares, which works, but you really only need i vertical lines and j horizontal ones - which is a lot less processing. Run a quicker loop with fewer calculations:

function fill_grid() {
        ctx.beginPath();
        ctx.fillStyle = 'black';
        ctx.fillRect(0,0,w,h);
        for (var i=0;i<=h;i+=cw)
        {
            ctx.moveTo(0,i);
            ctx.lineTo(w,i);
            ctx.moveTo(i,0);
            ctx.lineTo(i,h);
        }
        ctx.stroke();
    }

I would also only define line width and stroke colour once, as you initialise the canvas. You may not need to worry about this of course. But this kind of care can make a difference if you refresh the grid often to animate your snakes.

Upvotes: 1

Related Questions