如何检测对象是否位于画布元素上的绳索

How to detect if an object is at cordinates on canvas element?

本文关键字:元素 于画布 是否 何检测 检测 对象      更新时间:2023-09-26

我正在努力在画布上创建一个井字游戏。我目前卡在检测画布上的 x/y 绳索上是否已经有一个符号(X 或 O)的点。

我尝试使用 ImageData 来检查元素是否存在,但如果不存在任何元素,它会返回错误。我还想也许我可以为正方形或符号分配一个 ID。然而,从我所读到的内容来看,这似乎是不可能的。

任何帮助将不胜感激。

您可以在此处看到正在运行的游戏 http://jsfiddle.net/weeklygame/dvJ5X/30/

function TTT() {
    this.canvas = document.getElementById('ttt');
    this.context = this.canvas.getContext('2d');
    this.width = this.width;
    this.height = this.height;
    this.square = 100;
    this.boxes = [];
    this.turn = Math.floor(Math.random() * 2) + 1;
    this.message = $('.message');
};
var ttt = new TTT();
TTT.prototype.currentPlayer = function() {
    var symbol = (this.turn === 1) ? 'X' : 'O';
    ttt.message.html('It is ' + symbol + '''s turn');
};
// Draw the board
TTT.prototype.draw = function(callback) {
    // Draw Grid
    for(var row = 0; row <= 200; row += 100) {
        var group = [];
        for(var column = 0; column <= 200; column += 100) {
            group.push(column);
            this.context.strokeStyle = 'white';
            this.context.strokeRect(column,row,this.square,this.square);
        };
        this.boxes.push(group);
    };
    callback;
};
// Get center of the click area cordinates
TTT.prototype.cordinates = function(e) {
    var row = Math.floor(e.clientX / 100) * 100,
        column = Math.floor(e.clientY / 100) * 100;
    return [row, column];
};
// Check if the clicked box has symbol
TTT.prototype.check = function(row, column) {
};
// Get cordinates and set image in container
TTT.prototype.click = function(e) {
    var cordinates = ttt.cordinates(e),
        x = cordinates[0] + 100 / 2,
        y = cordinates[1] + 100 / 2,
        image = new Image();
    if (ttt.turn === 1) {
        image.src = 'http://s8.postimg.org/tdp7xn6lt/naught.png';
        ttt.turn = 2;
    } else {
        image.src = 'http://s8.postimg.org/9kd44xt81/cross.png';
        ttt.turn = 1;
    };
    ttt.context.drawImage(image, x - (image.width / 2), y - (image.height / 2));
    ttt.currentPlayer();
};
function render() {
    ttt.draw($('#ttt').on("click", ttt.click));
    ttt.currentPlayer();
};
(function init() {
    render();
})();

使用数组跟踪网格位置不是更容易吗?当您在网格上放置某些东西时,请在数组中分配该位置。这样,您不必想办法从画布上读取它,而只需在数组中查找即可。 这也允许您在需要时快速从数组中重新绘制画布,例如当屏幕调整大小时...

要检测单击了哪个字段,请遍历 9 个字段并检查单击的位置是否位于绘制字段的区域。

为了能够做到这一点,请存储字段的状态(位置以及其中是否有 X、O 或什么都没有)。您还应该将 9 个字段存储在一个数组中,以便您可以轻松地迭代它们。我会将其存储在二维数组 (3x3) 中。

function Field(x, y) {
    this.x = x;
    this.y = y;
    this.value = null; // Can be null, 'X' or 'O'
}

井字字段的初始化:

var fields = [
    [new Field(0,0), new Field(1,0), new Field(2,0)],
    [new Field(0,1), new Field(1,1), new Field(2,1)],
    [new Field(0,2), new Field(1,2), new Field(2,2)]
];

迭 代:

for (var y = 0; y <= 2; y++) {
    for (var x = 0; x <= 2; x++) {
        var field = fields[y][x];
        // Do something with the field.
    }
}

我会用模型坐标存储字段的位置。因此,您将坐标乘以一个值以获得在画布上绘制的坐标。