在URL上查看页面时,JavaScript函数的性能与在本地浏览器中查看页面时不同
我有以下网页,在HTML5画布上显示许多图像和一个“得分栏”:在URL上查看页面时,JavaScript函数的性能与在本地浏览器中查看页面时不同,javascript,html5-canvas,Javascript,Html5 Canvas,我有以下网页,在HTML5画布上显示许多图像和一个“得分栏”: <!DOCTYPE HTML> <html> <head> <style> body { margin: 0px; padding: 0px; } canvas{ border: 1px solid #9C9898; background:#F5F5F5; } </style> <div id="container"&g
<!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>
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);
}
}
/*此函数用于绘制级别1的元素*/
函数drawLevelOneElements(){
/*首先,清除画布*/
clearRect(0,0,myGameCanvas.width,myGameCanvas.height);
/*此行清除先前在画布上绘制的所有元素*/
/*然后重新绘制游戏元素*/
drawGameElements();
/*调用函数以启用拖放*/
canvasState(document.getElementById('gameCanvas');
/*创建四个描述区域,并将它们放置在画布底部附近*/
/*为描述区域创建圆角框*/
CanvasRenderingContext2D.prototype.drawDescriptionArea=函数(x、y、宽度、高度、半径、笔划){
如果(笔划类型==“未定义”){
笔划=真;
}
如果(半径类型==“未定义”){
半径=5;
}
this.beginPath();
这个。移动到(x+半径,y);
此.lineTo(x+宽度-半径,y);
这就是四次曲线(x+宽度,y,x+宽度,y+半径);
此.lineTo(x+宽度,y+高度-半径);
这就是四次曲线(x+宽度,y+高度,x+宽度-半径,y+高度);
此.lineTo(x+半径,y+高度);
这就是四次曲线(x,y+高度,x,y+高度-半径);
此.lineTo(x,y+半径);
这就是二次曲线(x,y,x+半径,y);
这个.closePath();
如果(笔划){
stroke();
}
}
背景。drawDescriptionArea(7040012070);
context.font='25pt Calibri';
strokeText(“资产”,90440);
背景。drawDescriptionArea(300、400、120、70);
strokeText(“责任”,310,440);
背景。drawDescriptionArea(540、400、120、70);
strokeText(“收入”,550440);
背景。drawDescriptionArea(75040018070);
strokeText(“支出”,760440);
/*现在将图像绘制到画布上*/
/*首先,为要绘制的图像的x&y坐标创建变量。
x&y坐标应该包含随机数,这样图像将
在画布上的随机位置绘制*/
var imageX=Math.floor(Math.random()*100);
var imageY=Math.floor(Math.random()*100);
var imageWidth=50;
var imageHeight=50;
/*创建图像将绘制到的位置的“表格”*/
var imagePositionsX=[20,80,140,200,260,320,380,440,500,560];
var imagePositionsY=[20,60,100,140,180,220,260,300,340,380];
/*从AssetImageArray绘制所有图像*/
/*使用while循环在数组中循环,获取每个项目并绘制它*/
var arrayIteration=0;
log('All Images Array.length:'+allImagesArray.length);/*在控制台中显示数组的长度,以检查它是否包含正确数量的图像*/
while(数组迭代
和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);
}
}
/*全局变量*/
var image=新图像();
/*此函数启动游戏,并调用游戏所需的所有其他函数*/
函数startName(){
预加载图像();
//drawGameElements();/*从函数startName()中删除此调用,以便在显示开始按钮时不会显示记分栏*/
drawStartButton();
/*将事件侦听器添加到画布,画布将调用drawLevelOneElements()
单击“开始”按钮时*/
myGameCanvas.addEventListener('click',函数(e){
console.log('click:'+e.pageX+'/'+e.pageY);
var mouseX=e.pageX-this.offsetLeft;
var mouseY=e.pageY-this.offsetTop;
如果((mouseX>260.5&&mouseX<410.5+179)和((mouseY>120&&mouseY<120+180)){/*出于某种原因,将“60”坐标更改为206会起作用*/
drawLevelOneElements();
init();
/*禁用事件侦听器以单击开始按钮,因为它将继续侦听单击*/
this.removeEventListener('click',arguments.callee,false);
}否则{
console.log(“无冲突”);
}
},假);
}
/*此函数用于绘制游戏元素*/
函数drawGameElements(){
/*为“得分栏”画一条线*/
上下文。移动到(0,25);
lineTo(1000,25);
stroke();
/*在左侧绘制当前级别/总级别,在右侧绘制当前分数*/
context.font=“11pt Calibri”/*Text fon
/* 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);
}
}
GET http://users.aber.ac.uk/eef8/project/development/dragimagestoboxes/drawLevelOneElements.js 404 (Not Found) users.aber.ac.uk:18
GET http://users.aber.ac.uk/eef8/project/development/dragimagestoboxes/images/startButton.png 404 (Not Found) users.aber.ac.uk:18
GET http://users.aber.ac.uk/eef8/project/development/dragimagestoboxes/images/liabilities/hirePurchase.jpg 404 (Not Found) users.aber.ac.uk:18
GET http://users.aber.ac.uk/eef8/project/development/dragimagestoboxes/images/liabilities/payeTax.jpg 404 (Not Found) users.aber.ac.uk:18
GET http://users.aber.ac.uk/eef8/project/development/dragimagestoboxes/images/expenses/direct/franchiseFee.jpg 404 (Not Found) users.aber.ac.uk:18
GET http://users.aber.ac.uk/eef8/project/development/dragimagestoboxes/images/liabilities/hirePurchase.jpg 404 (Not Found) users.aber.ac.uk:62
GET http://users.aber.ac.uk/eef8/project/development/dragimagestoboxes/images/expenses/direct/franchiseFee.jpg 404 (Not Found) users.aber.ac.uk:62
GET http://users.aber.ac.uk/eef8/project/development/dragimagestoboxes/images/liabilities/payeTax.jpg 404 (Not Found) users.aber.ac.uk:62