javascript - 在 HTML5 Canvas 上绘制 X 形状并检查与边框的碰撞

标签 javascript html html5-canvas

我正在使用 HTML 5 开发迷宫游戏。

这是我用来在 Canvas 上绘制“X”的函数(使用触摸板,用户将在迷宫中导航 X)。

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();       
}

问题出在checkcollision函数上,主要在这一段代码:

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

我正在寻找一种最佳方法来检查 Canvas 上“X”占用的所有空间。

我使用的代码中有更多注释。

问题: 1. 有时,X 会稍微超出边界 2. 有时,X 没有靠近,与边框之间存在几个像素。

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

我相信 getImageData 得到一个从 Angular 落的 x,y 位置开始的矩形。

所以也许有一种方法可以使用 checkx 和 checky 作为中心坐标来绘制它,并检索一个 16 像素宽的正方形

最佳答案

哇,写下问题已经很清楚了:

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

你们这些人

关于javascript - 在 HTML5 Canvas 上绘制 X 形状并检查与边框的碰撞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18110936/

相关文章:

javascript - JS基本功能不起作用

javascript - 为什么函数没有 [[Value]] 属性?

javascript - 如何通过 JavaScript 将值推送到 PHP 数组变量?

PHP - 动态更改变量

jquery - 如何使用 jQuery/CSS3 创建 'Slide-in gallery panels'?

Javascript html canvas 组织线条以防止重叠

html - 适用于不同屏幕的响应式 Canvas - 最好的方法是什么?

javascript - 更改整个页面内容的文本字体大小

html - ie7 float 右父宽度问题

html - 有没有办法将图像中的 GUI 转换为 html?