Использование операторов JS if для определения того, перетаскивается ли изображение в нужное место на холсте HTML5.

У меня есть несколько «перетаскиваемых» изображений на холсте HTML5. На холсте также отображается ряд изображений «окна описания», и пользователь должен перетащить каждое из перетаскиваемых изображений в соответствующее поле описания.

В настоящее время на холсте отображаются четыре поля описания, и у меня есть функция, которую я использую, чтобы определить, было ли изображение перетащено в одно из полей. Каждый раз, когда изображение перетаскивается в ящик, я проверяю, было ли оно перетащено в правильный ящик - если есть, изображение затем скрывается, но если нет, оно остается видимым.

Все перетаскиваемые изображения хранятся в одном массиве, и я проверяю, перетаскиваются ли они в нужное поле, используя их положение в массиве, т.е. если они находятся между позициями 0-9 в массиве, они относятся к ящику 1; если они находятся в позициях 10-19, они принадлежат ячейке 2 и т. д.

Я добавляю операторы if для каждого поля по одному, и в настоящее время он работает так, как задумано для первых двух полей. Сейчас я пытаюсь добавить код для третьего поля, но по какой-то причине, когда я добавляю это, код прерывается, и в консоли появляется ошибка ReferenceError.

Вот как сейчас выглядит функция:

function isHit(mouseX, mouseY, obj){
  console.log("isHit has been called from within if statement in mousemove function");
  console.log("draggingImage variable value = " +draggingImage);
  if(draggingImage == true){
    console.log("if dragging image == true statment is being called");
    console.log("Value of selectedImage = " + selectedImage);
    console.log("Value of selectedImageArrayLocation = " + selectedImageArrayLocation);
    if(mouseY > 250){
        //console.log("Value of obj.shape.index = " +obj.shape.index);
        if((mouseX > 80) && (mouseX < 200) && (selectedImageArrayLocation >= 0) && (selectedImageArrayLocation <= numImagesAssets)){
            console.log("Correct");
            document.getElementById('tipsParagraph').innerHTML = "Correct! This is an asset because it is an item that can be bought or sold for cash.";
            selectedImage.hide();
            console.log("selectedImage has been removed: " + selectedImage);
        }else if((mouseX > 80) && (mouseX < 200) && (selectedImageArrayLocation > numImagesAssets)){
            console.log("Incorrect");
            console.log("Selected image array location: " + selectedImageArrayLocation);
            document.getElementById('tipsParagraph').innerHTML = "Incorrect! This icon is not an asset. It is not a physical item that would be bought or sold for cash. ";

        }else if((mouseX > 310) && (mouseX < 430) && (selectedImageArrayLocation > numImagesAssets) && (selectedImageArrayLocation <= numImagesAssets + numImagesLiabilities)){
            document.getElementById('tipsParagraph').innerHTML = "Correct! This is a liability because it is an item or service that the company is required to make regular payments for. ";
            selectedImage.hide();
            console.log("selectedImage has been removed: " + selectedImage);
        }else if((mouseX > 310) && (mouseX < 430) && ((selectedImageArrayLocation <= numImagesAssets) || (selectedImageArrayLocation > numImagesAssets + numImagesLiabilities))){
            console.log("Incorrect. This icon is not a liability.");
            console.log("Selected image array location: " + selectedImageArrayLocation);
            document.getElementById('tipsParagraph').innerHTML = "Incorrect! This icon is not a liability. It is not an item or service that the company is required to make regular payments for. ";

        }else if((mouseX > 540) && (mouseX < 660) && ((selectedImageArrayLocation > numImagesAssets + numImagesLiabilities) && (selectedImageArrayLocation <= numImagesAssets + numImagesLiabilities + numImagesIncome))){
            document.getElementById('tipsParagraph').innerHTML = "Correct! This is a source of income because it is a product or service which the company sells to its customers for cash. ";
            selectedImage.hide();
            console.log("Selected image has been removed: " + selectedImage);
        }/*else if((mouseX > 540) && (mouseX < 660) && ((selectedImageArrayLocation <= numImagesAssets + numImagesLiabilities) && (selectedImageArrayLocation > numImagesAssets + numImagesLiabilities + numImagesIncome))){
            console.log("Incorrect. This icon is not a source of income.");
            console.log("Selected image array location: " + selectedImageArrayLocation);
            document.getElementById('tipsParagraph').innerHTML = "Incorrect! This icon is not a source of income.");
        } */
    }
  }
}

Операторы if расположены парами, поэтому первые два относятся к первому блоку описания, вторые два - ко второму и т. Д.

На данный момент у меня есть только первый оператор if, работающий для третьего поля описания ... Я написал для него второй оператор if точно так же, как и для предыдущих двух полей описания, но для некоторых причина, когда я раскомментирую это предложение 'else if', просматриваю свою страницу в браузере и перетаскиваю изображение в это поле описания, которое ему не принадлежит, я получаю консольную ошибку, которая гласит:

ReferenceError: isHit is not defined

Эта ошибка жалуется на строку:

var isItHit = isHit(mouseX, mouseY, obj);

который находится в моей функции mousemove, которая также вызывается всеми другими операторами if, поэтому я не понимаю, почему она решила сломаться, когда она вызывается на этот раз ... есть ли у кого-нибудь идеи?


person Noble-Surfer    schedule 21.03.2013    source источник


Ответы (1)


Ах, хорошо, я заметил, в чем проблема ... В строке document.getElementById в последнем предложении else if у меня было ) слишком много. Проблема была устранена путем изменения этой строки на:

document.getElementById('tipsParagraph').innerHTML = "Incorrect! This icon is not a source of income.";

т.е. удаление ) в конце строки.

person Noble-Surfer    schedule 21.03.2013