简体   繁体   中英

Drawing an X shape on a HTML5 canvas and checking for collisions with a border

I am working on a maze game in HTML 5.

Here is the function which I use to draw an "X" on the canvas (using the touchpad, the user will navigate the X through the labyrinth).

dim = 8;

function rect(x,y,xdim){
    ctx.beginPath();
    ctx.moveTo(x - xdim, y - xdim);
    ctx.lineTo(x + xdim, y + xdim);
    ctx.moveTo(x + xdim, y - xdim);
    ctx.lineTo(x - xdim, y + xdim);
    ctx.strokeStyle = '#FF5000';
    ctx.stroke();       
}

The problem is in the checkcollision function , mainly in this piece of code:

ctx.getImageData(checkx, checky, 16, 16);

I am looking for an optimal way to check all the space that is taken up by the "X" on the canvas.

There are more comments in the code i used.

Issues: 1. Sometimes, the X goes a little passed the border 2. Sometimes, the X doesn't get close, letting a few pixels between it and the border.

function checkcollision(checkx, checky){
        var collision = 0;
        /*
            User presses an arrow key

            Calculate where that would move the square to.

            Look at all of the pixels on the maze image that the square will cover
            in its new position (our square is 15x15 so we look at 225 pixels)

            Are any of the pixels black (the maze is white with black borders. 
            If a pixel is black that means the square would collide with a border)

            YES: then do not move

            NO: then move
        */
        var imgd = ctx.getImageData(checkx, checky, 15, 15);
        pix = imgd.data;
        for (var i = 0; n = pix.length, i < n; i += 4){
            if (pix[i] == 0) {
                collision = 1;
            } else if(pix[i] == 255 && pix[i + 1] == 0){
                winner = "yes";
            }
        }
        return collision;
    }

I believe the getImageData gets a rectangle which starts from the x,y position in a corner.

So maybe there is a way to draw it using the checkx and checky as the coordinates for the center and retrieve a square 16 pixels wide

Wow, writing the question made it clear:

var imgd = ctx.getImageData(checkx - xdim, checky - xdim, 16, 16);

Ty guys

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM