次のWebページがあり、HTML5キャンバスに多数の画像と「スコアバー」が表示されています。
<!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("images array length = " + images.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 canvasImage = new Kinetic.Image({
image: imageObj,
width: 50,
height: 50,
// puts the image in teh middle of the canvas
x: stage.getWidth() / 2 - 50 / 2,
y: 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
loadImages(sources, drawImage);
drawGameElements();
drawDescriptionBoxes();
};
</script>
最後のwindow.onload()
関数は、HTMLの本文の非表示セクションから大量の画像を取得しています。
HTMLで呼び出されている3つのJavaScriptファイルがあります。
drawdescriptionboxes.js
function drawDescriptionBoxes(){
var assetsDescriptionBox = new Image();
var liabilitiesDescriptionBox = new Image();
var incomeDescriptionBox = new Image();
var expenditureDescriptionBox = new Image();
assetsDescriptionBox.src = 'images/box.png';
liabilitiesDescriptionBox.src = 'images/box.png';
incomeDescriptionBox.src = 'images/box.png';
expenditureDescriptionBox.src = 'images/box.png';
context.drawImage(assetsDescriptionBox, 70, 400, 120, 70);
context.drawImage(liabilitiesDescriptionBox, 300, 400, 120, 70);
context.drawImage(incomeDescriptionBox, 530, 400, 120, 70);
context.drawImage(expenditureDescriptionBox, 760, 400, 120, 70);
context.strokeText("Assets", 100, 490);
context.strokeText("Liabilities", 325, 490);
context.strokeText("Income", 550, 490);
context.strokeText("Expenditure", 775, 490);
}
function dragImageToBox(){
}
drawleveloneelements.js:
/* This function draws the elements for level 1. */
function drawLevelOneElements(){
/*First, clear the canvas */
context.clearRect(0, 0, myGameCanvas.width, myGameCanvas.height);
/*This line clears all of the elements that were previously drawn on the canvas. */
/*Then redraw the game elements */
drawGameElements();
/*Call the function to enable drag and drop */
canvasState(document.getElementById('gameCanvas'));
/*Create the four description areas, and place them near the bottom of the canvas */
/*Create boxes with rounded corners for the description areas */
CanvasRenderingContext2D.prototype.drawDescriptionArea = function(x, y, width, height, radius, stroke){
if(typeof stroke == "undefined" ){
stroke = true;
}
if(typeof radius === "undefined"){
radius = 5;
}
this.beginPath();
this.moveTo(x + radius, y);
this.lineTo(x + width - radius, y);
this.quadraticCurveTo(x + width, y, x + width, y + radius);
this.lineTo(x + width, y + height - radius);
this.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
this.lineTo(x + radius, y + height);
this.quadraticCurveTo(x, y + height, x, y + height - radius);
this.lineTo(x, y + radius);
this.quadraticCurveTo(x, y, x + radius, y);
this.closePath();
if(stroke){
context.stroke();
}
}
context.drawDescriptionArea(70, 400, 120, 70);
context.font = '25pt Calibri';
context.strokeText('Asset', 90, 440);
context.drawDescriptionArea(300, 400, 120, 70);
context.strokeText('Liability', 310, 440);
context.drawDescriptionArea(540, 400, 120, 70);
context.strokeText('Income', 550, 440);
context.drawDescriptionArea(750, 400, 180, 70);
context.strokeText('Expenditure', 760, 440);
/*Now draw the images to the canvas */
/*First, create variables for the x & y coordinates of the image that will be drawn.
the x & y coordinates should hold random numbers, so that the images will be
drawn in random locations on the canvas.*/
var imageX = Math.floor(Math.random()*100);
var imageY = Math.floor(Math.random()*100);
var imageWidth = 50;
var imageHeight = 50;
/*Create a 'table' of positions that the images will be drawn to */
var imagePositionsX = [20, 80, 140, 200, 260, 320, 380, 440, 500, 560];
var imagePositionsY = [20, 60, 100, 140, 180, 220, 260, 300, 340, 380];
/*Draw all images from assetsImageArray */
/*Use a while loop to loop through the array, get each item and draw it. */
var arrayIteration = 0;
console.log('All Images Array length: ' + allImagesArray.length); /*Display the length of the array in the console, to check it's holding the correct number of images. */
while(arrayIteration < allImagesArray.length){
//var randomPositionX = Math.floor(Math.random()*10);
//var randomPositionY = Math.floor(Math.random()*10);
context.drawImage(allImagesArray[arrayIteration], imageX, imageY, imageWidth, imageHeight); /*Declare variables for image height and width, so it can be accessed elsewhere */
//allImagesArray[arrayIteration].setDraggable = "true";
allImagesArray[arrayIteration].setAttribute('draggable', 'true');
console.log(arrayIteration); /*Display the current array position that's being drawn */
arrayIteration = arrayIteration+1;
/*Now try changing the values of imageX & imageY so that the next image is drawn to a
different location*/
//imageX = imagePositionsX[randomPositionX]; /* imageX+(Math.floor(Math.random()*100)); */
//imageY = imagePositionsY[randomPositionY]; /* imageY+(Math.floor(Math.random()*100)); */
imageX = Math.floor(Math.random()*950);
imageY = Math.floor(Math.random()*350);
}
}
およびstartgamedrawgameelementsdrawstartbutton.js:
/* Global variables */
var image = new Image();
/* This function starts the game, and calls all of the other functions required to play the game */
function startGame(){
preLoadImages();
// drawGameElements(); /*Remove this call from function startGame(), so that the score bar doesn't show while the start button is displayed */
drawStartButton();
/*Add event listener to the canvas, which will call drawLevelOneElements()
when the start button is clicked*/
myGameCanvas.addEventListener('click', function(e){
console.log('click: ' + e.pageX + '/' + e.pageY);
var mouseX = e.pageX - this.offsetLeft;
var mouseY = e.pageY - this.offsetTop;
if((mouseX > 260.5 && mouseX < 410.5+179) && (mouseY > 120 && mouseY < 120+180)){ /* Changing the '60' coordinates to 206 works for some reason */
drawLevelOneElements();
init();
/*Disable the event listener for clicking start button, because it continues to listen for a click */
this.removeEventListener('click',arguments.callee,false);
} else {
console.log('no collision');
}
}, 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, currentScorePositionX, currentScorePositionY);
}
/* This function draws a start button which the user can click to start the game */
function drawStartButton(){
image.onload = function(){
context.drawImage(image, 410.5, 120);
};
image.src = "startButton.png";
/* Now I need to add an event listener to the area of the canvas on
on which the button image is displayed, in order to 'listen' for
a click on the button */
var boundingBox = myGameCanvas.getBoundingClientRect();
//var mouseX = (mouse_event.clientX-boundingBox.left) * (myGameCanvas.width/boundingBox.width);
//var mouseY = (mouse_event.clientY-boundingBox.top) * (myGameCanvas.height/boundingBox.height);
boundingBox.onmousemove = function(e){
var mouseX = e.pageX - this.offsetLeft;
var mouseY = e.pageY - this.offsetTop;
var pixels = context.getImageData(mouseX, mouseY, 1, 1);
}
}
ファイルを右クリックして[Firefoxで開く]を選択してブラウザでページを表示すると、すべての画像が表示され、キャンバス上でドラッグアンドドロップできます。ただし、私が見つけたURL(http://users.aber.ac.uk/eef8/project/development/dragimagestoboxes/ )でページを表示すると、表示された画像の1つをクリックすると、すべてが消えます。キャンバスから。
ローカルに保存したすべてのファイルがサーバーに保存されたものとまったく同じであることを考えると、これがなぜであるかを理解することはできません。
誰かアイデアはありますか?