簡體   English   中英

JavaScript Canvas檢查矩形是否包含矩形

[英]JavaScript Canvas check if rectangle include rectangle

我有兩個對象數組。 例:

var boxes = [],
    coins = [],
    k = 0;

boxes.push({
    x: 300,
    y: 350,
    width: 500,
    height: 500
});

for (k; k < 30; k++) {
    coins.push({
        x: Math.floor(Math.random() * (10 - 4) + 4) * 100,
        y: Math.floor(Math.random() * (4 - 1) + 1) * 100,
        width:25,
        height:25
    });
}

從那以后,我使用for用於繪制這些東西。 問題是有時候硬幣會裝在盒子里。 如何檢查硬幣是否在箱子范圍內? 我當時正在考慮計算方盒和硬幣,但我不知道該如何完成。

var i = 0,
    j = 0;

for (i; i < coins.length; i++) {
    for (j; j < boxes.length; j++) {

        if (boxes[j].x + boxes[j].width /* something */ coins[i].x + coins[i].width && boxes[j].y + boxes[j].height /* something */ coins[i].y + coins[i].height) {
            /* do nothing */
        } else { 
            ctx.fillRect(coins[i].x, coins[i].y, coins[i].width, coins[i].height);
        }

    }
}

有人知道如何完成嗎? 也許還有其他方法? 我只能使用純JavaScript。

謝謝你的幫助。

這是獲得成功的if條件

if (
    (boxes[j].x < (coins[i].x + coins[i].width) &&  (boxes[j].x + boxes[j].width) > coins[i].x) &&
    (boxes[j].y < (coins[i].y + coins[i].height) &&  (boxes[j].y + boxes[j].height) > coins[i].y)
) {
    /* HIT - Do nothing */
} else {
    /* No Hit - Draw the coin */
}

我沒有測試它,但是我確定它可以工作...


編輯:

順便說一句,我注意到您沒有在for循環中重設ij var,您至少應該在第二個循環( j )中執行此操作,否則循環將無法工作。

for (i = 0; i < coins.length; i++) {
    for (j = 0; j < boxes.length; j++) {

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM