2013-02-15 155 views
1

我正在使用JavaScript製作基於HTML5畫布的遊戲。遊戲只是一個簡單的遊戲,畫布上顯示了許多圖像以及一些描述框。用戶需要將每個圖像拖放到相應的描述框中。函數內部的JavaScript-調用函數

目前,我有畫布顯示圖像和說明框。這些會在頁面加載後立即顯示出來,但是,我想添加一個「開始按鈕」,在顯示圖像和說明框等之前用戶需要點擊,然後他們開始玩遊戲。

爲我的網頁的代碼目前看起來是這樣的:

<!DOCTYPE HTML> 
<html> 
    <head> 
    <style> 
    body { 
    margin: 0px; 
    padding: 0px; 
    } 
    canvas{ 
    border: 1px solid #9C9898; 
    background:#F5F5F5; 
    } 
</style> 
<div id="container"></div> 
<script src="kinetic.js"></script> 
<script src="drawdescriptionboxes.js"></script> 
<script src="drawLevelOneElements.js"></script> 
<script src="startGameDrawGameElementsDrawStartButton.js"></script> 
<script> 
/*Add the game elements' global variables */ 
var currentLevel = 1; 
var totalLevels = 3; 
var currentScore = 0; 
var currentScorePositionX = 950; 
var currentScorePositionY = 10; 

/*Add code to draw images to random locations here */ 
    //var imageX = Math.floor(Math.random()*950); 
    //var imageY = Math.floor(Math.random()*450); 

    var stage = new Kinetic.Stage({ 
     container: "container", 
     width: 1000, 
     height: 500 
    }); 
    var imagesLayer = new Kinetic.Layer(); 
    var canvas = imagesLayer.getCanvas(); 
    var context = canvas.getContext("2d"); 
    console.log("Foo "); 

/*Load the images from the HTML into the JavaScript */ 
function loadImages(sources, callback){ 
    var imagesDir = ""; 
    var images = {}; 
    var loadedImages = 0; 
    var numImages = 0; 

    //console.log("length " + sources.length); 
    for (var src in sources){ 
     numImages++; 
    } 
    //console.log("Num Images " + numImages); 

    var index=0; 
    console.log("length " + sources.length); 
    for (index=0;index < numImages ;index++){ 
     console.log(index); 
     images[index] = new Image(); 
     images[index].src = sources[index]; 
     console.log("Adding " + sources[index]); 
     callback(images[index]); 
     console.log("sources array length = " + sources.length); 
    } 

    stage.add(imagesLayer); // should only be added once!! 
} 

/*Function to check whether the item being dragged is near its description box */ 
function isNearDescriptionBox(itemImage, descriptionBox){ 
    var ii = itemImage; 
    var db = descriptionBox; 
    if(ii.attrs.x > db.x - 20 && ii.attrs.x < db.x + 20 && ii.attrs.y > db.y - 20 && ii.attrs.y < db.y +20){ 
     return true; 
    }else{ 
     return false; 
    } 
} 

/* This function draws the game elements */ 
function drawGameElements(){ 
    /* Draw a line for the 'score bar'. */ 
    context.moveTo(0, 25); 
    context.lineTo(1000, 25); 
    context.stroke(); 

    /* Draw current level/ total levels on the left, and current score on the right. */ 
    context.font = "11pt Calibri"; /* Text font & size */ 
    context.strokeStyle = "black"; /* Font colour */ 
    context.strokeText(currentLevel + "/" + totalLevels, 10, 15); 
    context.strokeText(currentScore, 750, 15); 
} 

function initStage(images){ 
    var stage = new Kinetic.Stage({ 
     container: "container", 
     width: 1000, 
     height: 500 
    }); 
    var descriptionLayer = new Kinetic.Layer(); 
    //var imagesLayer = new Kinetic.Layer(); 
    var allImages = []; 
    var currentScore = 0; 

    var descriptionBoxes = { 
     assetsDescriptionBox: { 
      x: 70, 
      y: 400 
     }, 
     liabilitiesDescriptionBox: { 
      x: 300, 
      y: 400 
     }, 
     incomeDescriptionBox: { 
      x: 530, 
      y: 400 
     }, 
     expenditureDescriptionBox: { 
      x: 760, 
      y: 400 
     }, 
    }; 

    /*Code to detect whether image has been dragged to correct description box */ 
    for (var key in sources){ 
     /*Anonymous function to induce scope */ 
     (function(){ 
      var privateKey = key; 
      var imageSource = sources[key]; 

      /*Check if image has been dragged to the correct box, and add it to that box's 
       array and remove from canvas if it has */ 
      canvasImage.on("dragend", function(){ 
       var descriptionBox = descriptionBoxes[privateKey]; 
       if(!canvasImage.inRightPlace && isNearDescriptionBox(itemImage, descriptionBox)){ 
        context.remove(canvasImage); 
        /*Will need to add a line in here to add the image to the box's array */ 
       } 
      }) 

     })(); 
    } 

} 

function drawImage(imageObj) { 
    //var layer = new Kinetic.Layer(); 

    //var imageX = Math.floor(Math.random()*950); 
    //var imageY = Math.floor(Math.random()*450); 

    /*Got the code from generating random coordinates from: 
     http://stackoverflow.com/questions/4959975/random-between-two-numbers-in-javascript*/ 
    function randomPosition(from, to){ 
     return Math.floor(Math.random()*(to-from+1)+from); 
    } 

    var canvasImage = new Kinetic.Image({ 
     image: imageObj, 
     width: 50, 
     height: 50, 
     // puts the image in teh middle of the canvas 
     x: randomPosition(0, 950), //imageX, //stage.getWidth()/2 - 50/2, 
     y: randomPosition(30, 350), //imageY, //stage.getHeight()/2 - 50/2, 
     draggable: true 
    }); 

    // add cursor styling 
    canvasImage.on('mouseover', function() { 
     document.body.style.cursor = 'pointer'; 
    }); 
    canvasImage.on('mouseout', function() { 
     document.body.style.cursor = 'default'; 
    }); 

    imagesLayer.add(canvasImage); 
} 

/*This code loads the images to the canvas when the browser window loads */ 
window.onload = function(){ 
    var sources = []; 
     sources[0] = document.getElementById("building").src, 
     sources[1] = document.getElementById("chair").src, 
     sources[2] = document.getElementById("drink").src, 
     sources[3] = document.getElementById("food").src, 
     sources[4] = document.getElementById("fridge").src, 
     sources[5] = document.getElementById("land").src, 
     sources[6] = document.getElementById("money").src, 
     sources[7] = document.getElementById("oven").src, 
     sources[8] = document.getElementById("table").src, 
     sources[9] = document.getElementById("van").src, 

     sources[10] = document.getElementById("burger").src, 
     sources[11] = document.getElementById("chips").src, 
     sources[12] = document.getElementById("drink").src, 
     sources[13] = document.getElementById("franchiseFee").src, 
     sources[14] = document.getElementById("wages").src, 

     sources[15] = document.getElementById("admin").src, 
     sources[16] = document.getElementById("cleaners").src, 
     sources[17] = document.getElementById("electricity").src, 
     sources[18] = document.getElementById("insurance").src, 
     sources[19] = document.getElementById("manager").src, 
     sources[20] = document.getElementById("rates").src, 
     sources[21] = document.getElementById("training").src, 
     sources[22] = document.getElementById("water").src, 

     sources[23] = document.getElementById("burger").src, 
     sources[24] = document.getElementById("chips").src, 
     sources[25] = document.getElementById("drink").src, 

     sources[26] = document.getElementById("creditors").src, 
     sources[27] = document.getElementById("electricity").src, 
     sources[28] = document.getElementById("food").src, 
     sources[29] = document.getElementById("hirePurchase").src, 
     sources[30] = document.getElementById("loan").src, 
     sources[31] = document.getElementById("overdraft").src, 
     sources[32] = document.getElementById("payeTax").src, 
     sources[33] = document.getElementById("tax").src; 

    drawStartButton(); 
    loadImages(sources, drawImage); 
    //drawGameElements(); 
    //drawDescriptionBoxes(); 

}; 

我也有在頁面,在那裏我已經加載的所有圖像的<body></body>一個隱藏的部分將被首先使用到HTML ,然後使用JS操縱它們。

當前,當我在瀏覽器中查看頁面時,sources陣列中的所有圖像都隨機顯示在畫布上,並附帶說明框,評分欄和開始按鈕。

但是,我想要發生的事情是,當頁面初始加載時,只有開始按鈕顯示在畫布上,然後當用戶單擊它時,其他所有內容都會顯示。

據推測,要做到這一點,我想刪除/在windows.onload = function(){...}函數結束註釋掉所有的函數的調用除了drawStartButton(),然後還要到其他函數調用在連接到一個onmousedown事件開始按鈕?

但是,出於某種原因,當我在此函數結束時將對loadImages(sources, drawImage);的調用註釋掉,然後再次在瀏覽器中查看我的頁面時,畫布不再顯示在頁面上。我本來期望畫布仍然存在,只是沒有顯示圖像。有沒有人有任何想法,爲什麼這沒有發生,我怎麼能說得對?

的代碼爲我loadImages(sources, drawImage);功能是:

function loadImages(sources, callback){ 
    var imagesDir = ""; 
    var images = {}; 
    var loadedImages = 0; 
    var numImages = 0; 

    //console.log("length " + sources.length); 
    for (var src in sources){ 
     numImages++; 
    } 
    //console.log("Num Images " + numImages); 

    var index=0; 
    console.log("length " + sources.length); 
    for (index=0;index < numImages ;index++){ 
     console.log(index); 
     images[index] = new Image(); 
     images[index].src = sources[index]; 
     console.log("Adding " + sources[index]); 
     callback(images[index]); 
     console.log("sources array length = " + sources.length); 
    } 

    stage.add(imagesLayer); // should only be added once!! 
} 

我不明白爲什麼刪除這個函數的調用將被顯示在頁面上停止畫布...任何想法?

回答

0

函數的最後一行,

stage.add(imagesLayer); // should only be added once!! 

添加層的階段。而舞臺是一個容器(例如div), 該圖層是實際的畫布。

如果您沒有撥打loadImages(),那麼該層永遠不會被添加到DOM中,因爲該行永遠不會運行。

+0

啊,好吧,這是有道理的。輝煌!非常感謝! – someone2088 2013-02-15 13:37:42

+0

那麼我會如何設置'onmousedown'來調用我想在開始按鈕圖像上檢測到mousedown時所需的功能?據推測,我需要創建一個JS變量,它使用'var startButton = document.getElementById(「startButton」)。src;'來保存啓動按鈕圖像,然後它會像'startButton.onmousedown function(){調用函數} ;'? – someone2088 2013-02-15 13:46:31

+0

因爲您正在使用畫布或Kinetic.js,所以確實不是那麼簡單。 *(也是.src將是圖像的URL,而不是DOM元素)*我假設你使用動力學。js的開始按鈕,而不是隻是定位按鈕的絕對?在這種情況下,請查看本教程以獲取kinetic事件:http://www.html5canvastutorials.com/kineticjs/html5-canvas-path-mouseover/ – MildlySerious 2013-02-15 13:50:20