How to take the data? - javascript
I am learning to use neural networks, and have encountered a problem.
I can not figure out how to convert data for a neural network.
As I understand it, I need to normalize the data, after normalization and learning, the answer is always averaged.
https://jsfiddle.net/eoy7krzj/
<html>
<head>
<script src="https://cdn.rawgit.com/BrainJS/brain.js/5797b875/browser.js"></script>
</head>
<body>
<div>
<button onclick="train()">train</button><button onclick="Generate.next(); Generate.draw();">generate</button><button onclick="calculate()">calculate</button>
</div>
<canvas id="generate" style="border: 1px solid #000"></canvas>
</body>
<script type="text/javascript">
var trainData = [];
function randomInteger(min, max) {
var rand = min - 0.5 + Math.random() * (max - min + 1)
//rand = Math.round(rand);
return rand;
}
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
var Generate = new function(){
var canvas = document.getElementById('generate');
var ctx = canvas.getContext('2d');
var elem = {
input: [],
output: []
}
var size = {
width: 240,
height: 140
}
canvas.width = 500;
canvas.height = 250;
this.next = function(){
this.build();
trainData.push({
input: elem.input,
output: elem.output
});
}
this.clear = function(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
this.draw = function(){
this.clear();
this.item(elem.input, function(item){
ctx.strokeStyle = "green";
ctx.strokeRect(item[0], item[1], item[2], item[3]);
})
this.item(elem.output, function(item){
ctx.strokeStyle = "blue";
ctx.strokeRect(item[0], item[1], item[2], item[3]);
})
}
this.item = function(where, call){
for (var i = 0; i < where.length; i+=4) {
var input = [
where[i],
where[i+1],
where[i+2],
where[i+3],
];
this.denormalize(input);
call(input)
}
}
this.normalize = function(input){
input[0] = input[0] / 500;
input[1] = input[1] / 250;
input[2] = input[2] / 500;
input[3] = input[3] / 250;
}
this.denormalize = function(input){
input[0] = input[0] * 500;
input[1] = input[1] * 250;
input[2] = input[2] * 500;
input[3] = input[3] * 250;
}
this.empty = function(add){
var data = [];
for (var i = 0; i < add; i++) {
data = data.concat([0,0,0,0]);
}
return data;
}
this.build = function(){
var output = [];
var input = [];
size.width = randomInteger(100,500);
size.height = randomInteger(50,250);
var lines = 1;//Math.round(size.height / 100);
var line_size = 0;
var line_offset = 0;
for(var i = 0; i < lines; i++){
line_size = randomInteger(30,Math.round(size.height / lines));
var columns = Math.round(randomInteger(1,3));
var columns_width = 0;
var columns_offset = 0;
for(var c = 0; c < columns; c++){
columns_width = randomInteger(30,Math.round(size.width / columns));
var item = [
columns_offset + 10,
line_offset + 10,
columns_width - 20,
line_size - 20
];
this.normalize(item);
input = input.concat(item);
columns_offset += columns_width;
}
var box = [
0,
line_offset,
columns_offset,
line_size
]
this.normalize(box);
output = output.concat(box);
line_offset += line_size + 10;
}
elem.input = input.concat(this.empty(5 - Math.round(input.length / 4)));
elem.output = output.concat(this.empty(2 - Math.round(output.length / 4)));
}
this.get = function(){
return elem.input;
}
this.calculate = function(result, stat){
console.log('brain:',result);
this.item(result, function(item){
ctx.strokeStyle = "red";
ctx.strokeRect(item[0], item[1], item[2], item[3]);
})
}
this.train = function(){
for(var i = 0; i < 40; i++){
this.next();
}
}
}
Generate.train();
Generate.log = true;
var net,stat;
function train(){
net = new brain.NeuralNetwork({ hiddenLayers: [8,4]});
stat = net.train(trainData,{log: true, iterations: 250,learningRate: 0.01,errorThresh:0.05});
console.log('stat:',stat)
}
function calculate(){
Generate.calculate(net.run(Generate.get()))
}
</script>
</html>
My goal is to train the network to find the elements and show their sizes.
Procedure:
Click to train
Click generate
Click to calculate
As a result, the network shows average results and red indicates that the network has found.
Maybe not so I transfer the data, can on another it is necessary?
Related
Java Script Quick Sort Working in Terminal But Not Web
I am building a website which makes a random list of numbers and quick sorts it with a visualization. When I run the function in the script section of my HTML file, it does not work correctly, however it works fine when I run it as a js file. Is there any reason for this? The quick sort function is at the bottom. <!DOCTYPE html> <html> <H1> Representation </H1> <h2></h2> <body> <button id='Quick Sort' onclick="quicksort()">Quick Sort</button> <canvas id="myCanvas" width="1400" height="650" style="border:1px solid #2a1baf;"></canvas> <input type="range" min="4" max="1000" value="1" class="slider" id="slider"> <p>Amount of Rectangles: <span id="choice"></span></p> <script> var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); var setup = true; var slider = document.getElementById("slider"); var slideText = document.getElementById("choice"); var size = 4; slideText.innerHTML = size; if (setup) { var arr = reset(size); setup = false; } var button = document.getElementById('Quick Sort'); slider.oninput = function() { slideText.innerHTML = this.value; size = this.value; ctx.clearRect(0, 0, c.width, c.height); arr = reset(size); } function reset(size) { nums = []; ar = []; for (i = 1; i <= size; i++) { nums.push(i); } while (nums.length > 0) { const random = Math.floor(Math.random() * nums.length); ar.push(nums[random]); nums.splice(random, 1); } ctx.beginPath(); for (var i = 0; i < size; i++) { ctx.rect(i * (1400 / size), 0, 1400 / size, 600 / (size) * ar[i]); } ctx.stroke(); return ar; } function bin_search(arr, val, start, end) { if (start == end) { if (arr[start] > val) { return start; } else { return start + 1; } } if (start > end) { return start; } var mid = Math.floor((start + end) / 2); if (arr[mid] < val) { return bin_search(arr, val, mid + 1, end); } else if (arr[mid] > val) { return bin_search(arr, val, start, mid - 1); } else { return mid; } } function quicksort() { for (var i = 1; i < arr.length; i++) { val = arr[i]; j = bin_search(arr, val, 0, i - 1); slice2 = arr.slice(j, i); slice3 = arr.slice(i + 1); arr = arr.slice(0, j); arr.push(val); arr = arr.concat(slice2); arr = arr.concat(slice3); ctx.beginPath(); for (var i = 0; i < size; i++) { ctx.rect(i * (1400 / size), 0, 1400 / size, 600 / (size) * ar[i]); } ctx.stroke(); } } </script> </body> </html>
Your problem is due to var declaration - using let for the for loops would fix your issue like: function quicksort() { for (let i = 1; i < arr.length; i++) { val = arr[i]; j = bin_search(arr, val, 0, i - 1); slice2 = arr.slice(j, i); slice3 = arr.slice(i + 1); arr = arr.slice(0, j); arr.push(val); arr = arr.concat(slice2); arr = arr.concat(slice3); ctx.beginPath(); for (let i = 0; i < size; i++) { ctx.rect(i * (1400 / size), 0, 1400 / size, 600 / (size) * ar[i]); } ctx.stroke(); } } I will not comment that many variables are missing their declaration
How to run u2net model with ONNX in browser (client side)?
I am trying to run u2net model in browser, I have converted the pytorch u2netp model into ONNX model and wrote the following code to run it but the results very poor. I followed the same preprocessing steps as that of python script but did not get the results. I was not able to find onnx functions to perform the preprocessing so I have used for loops to change the values in each channel. <!DOCTYPE html> <html> <header> <title>ONNX Runtime JavaScript examples: Quick Start - Web (using script tag)</title> <input id="image-selector" type="file" style="top:10px;left:10px" > <button id="predict-button" class="btn btn-dark float-right" style="top:10px;left:70px" >Predict</button> <img id="selected-image" src="" /> <canvas id="canvas" width =320px height=320px ></canvas> </header> <body> <!-- import ONNXRuntime Web from CDN --> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/onnxruntime-web/dist/ort.min.js"></script> <script> $("#image-selector").change(function () { let reader = new FileReader(); reader.onload = function () { let dataURL = reader.result; $("#selected-image").attr("src", dataURL); } let file = $("#image-selector").prop("files")[0]; reader.readAsDataURL(file); }); $("#predict-button").click(async function (){ const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); const session = await ort.InferenceSession.create('./u2netp.onnx').then(console.log("model loaded")); const inputNames = session.inputNames; const outputNames = session.outputNames; console.log('inputNames', inputNames) console.log('outputNames', outputNames) let image = $("#selected-image").get(0); console.log("image.naturalHeight", image.naturalHeight) console.log("image.naturalWidth", image.naturalWidth) var oc = document.createElement('canvas'), octx = oc.getContext('2d'); oc.width = 320; oc.height = 320; octx.drawImage(image, 0, 0, oc.width, oc.height); var input_imageData = octx.getImageData(0, 0, 320, 320); var floatArr = new Float32Array(320 * 320 * 3) var j = 0 for (let i = 1; i < input_imageData.data.length+1; i ++) { if(i % 4 != 0){ floatArr[j] = (input_imageData.data[i-1].toFixed(2))/255; // red color j = j + 1; } } console.log("floatArr1", floatArr) for (let i = 1; i < floatArr.length+1; i += 3) { floatArr[i-1] = (floatArr[i-1] - 0.485)/0.229 // red color floatArr[i] = (floatArr[i] - 0.456)/0.224 // green color floatArr[i+1] = (floatArr[i+1] - 0.406)/0.225 // blue color } console.log("floatArr2", floatArr) const input = new ort.Tensor('float32', floatArr, [1, 3, 320, 320]) a = inputNames[0] console.log("a", a) const feeds = {"input.1": input}; console.log("feeds", feeds) const results = await session.run(feeds).then(); const pred = Object.values(results)[0] console.log('pred', pred) console.log('pred.data.length', pred.data.length) console.log('pred.data[0]', Math.round(pred.data[0]*255)) var myImageData = ctx.createImageData(320, 320); for (let i = 0; i < pred.data.length*4; i += 4) { var pixelIndex = i; if(i != 0){ t = i/4; } else{ t = 0; } myImageData.data[pixelIndex ] = Math.round(pred.data[t]*255); // red color myImageData.data[pixelIndex + 1] = Math.round(pred.data[t]*255); // green color myImageData.data[pixelIndex + 2] = Math.round(pred.data[t]*255); // blue color myImageData.data[pixelIndex + 3] = 255; } ctx.putImageData(myImageData, 10, 10); console.log("myImageData", myImageData) }); </script> </body> </html>
Needed to transpose the image data array before passing it to the model. <!DOCTYPE html> <html> <header> <title>ONNX Runtime JavaScript examples: Quick Start - Web (using script tag)</title> <input id="image-selector" type="file" style="top:10px;left:10px" > <button id="predict-button" class="btn btn-dark float-right" style="top:10px;left:70px" >Predict</button> <img id="selected-image" src="" /> <canvas id="canvas" width =320px height=320px ></canvas> </header> <body> <!-- import ONNXRuntime Web from CDN --> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/onnxruntime-web/dist/ort.min.js"></script> <script> $("#image-selector").change(function () { let reader = new FileReader(); reader.onload = function () { let dataURL = reader.result; $("#selected-image").attr("src", dataURL); } let file = $("#image-selector").prop("files")[0]; reader.readAsDataURL(file); }); // async function main() { $("#predict-button").click(async function (){ const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); const session = await ort.InferenceSession.create('./u2netp.onnx').then(console.log("model loaded")); // input_name = getInputs(); const inputNames = session.inputNames; const outputNames = session.outputNames; let image = $("#selected-image").get(0); var oc = document.createElement('canvas'), octx = oc.getContext('2d'); oc.width = 320; oc.height = 320; octx.drawImage(image, 0, 0, oc.width, oc.height); var input_imageData = octx.getImageData(0, 0, 320, 320); console.log("input_imageData",input_imageData.data) var floatArr = new Float32Array(320 * 320 * 3) var floatArr1 = new Float32Array(320 * 320 * 3) var floatArr2 = new Float32Array(320 * 320 * 3) var j = 0 for (let i = 1; i < input_imageData.data.length+1; i ++) { if(i % 4 != 0){ floatArr[j] = (input_imageData.data[i-1].toFixed(2))/255; // red color j = j + 1; } } console.log("floatArr", floatArr) for (let i = 1; i < floatArr.length+1; i += 3) { floatArr1[i-1] = (floatArr[i-1] - 0.485)/0.229 // red color floatArr1[i] = (floatArr[i] - 0.456)/0.224 // green color floatArr1[i+1] = (floatArr[i+1] - 0.406)/0.225 // blue color } var k = 0 for (let i = 0; i < floatArr.length; i += 3) { floatArr2[k] = floatArr[i] // red color k = k + 1 } console.log("k", k) var l = 102400 for (let i = 1; i < floatArr.length; i += 3) { floatArr2[l] = floatArr[i] // red color l = l + 1 } console.log("l", l) var m = 204800 for (let i = 2; i < floatArr.length; i += 3) { floatArr2[m] = floatArr[i] // red color m = m + 1 } const input = new ort.Tensor('float32', floatArr2, [1, 3, 320, 320]) a = inputNames[0] const feeds = {"input.1": input}; const results = await session.run(feeds).then(); const pred = Object.values(results)[0] var myImageData = ctx.createImageData(320, 320); for (let i = 0; i < pred.data.length*4; i += 4) { var pixelIndex = i; if(i != 0){ t = i/4; } else{ t = 0; } myImageData.data[pixelIndex ] = Math.round(pred.data[t]*255); // red color myImageData.data[pixelIndex + 1] = Math.round(pred.data[t]*255); // green color myImageData.data[pixelIndex + 2] = Math.round(pred.data[t]*255); // blue color myImageData.data[pixelIndex + 3] = 255; } ctx.putImageData(myImageData, 10, 10); }); </script> </body> </html>
Force redraw during sort function execution in order to animate the steps
I have been trying to make an animated bubble sort in JS but every time I run the code it goes from a random order to sorted instantaneously. How do I make it redraw and stall for a set amount of time after every time I swap two things in the array of colour codes. <html> <body> <canvas id="myCanvas" width="300" height="700" style="border:1px solid #d3d3d3;"> </canvas> <script> function swap(nums, pos1,pos2) { var a = nums[pos1]; nums[pos1] = nums[pos2]; nums[pos2] = a; } function shuffle(nums) { for (var i = 0; i < 1000; i++) { var num1 = Math.floor((Math.random())*26); var num2 = Math.floor((Math.random())*26); swap(nums,num1,num2); } } function sleep(seconds) { var e = new Date().getTime() + (seconds * 1000); while (new Date().getTime() <= e) {} } function drawIt(nums) { var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); for (var i = 0; i < nums.length; i++) { var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); ctx.beginPath(); ctx.rect(10, i * 20 + 10, 50, 20); ctx.stroke(); ctx.fillStyle = "rgba(" + nums[i] + ", " + nums[i] + ", " + nums[i] + ", 1)"; ctx.fill(); } } var nums = new Array(); for (var i = 0; i<=250; i+=10) { nums[i/10] = i; } shuffle(nums); drawIt(nums); for (var i = 0; i < nums.length-1; i++) { for (var j = i+1; j < nums.length; j++) { if (nums[i] > nums[j]) { swap(nums, i,j); drawIt(nums); } } } </script> </body> </html> I have tried to use setTimeout() but nothing worked. EDIT: Is this what you meant because this still isn't working. <html> <body> <canvas id="myCanvas" width="300" height="800" style="border:1px solid #d3d3d3;"> </canvas> <script> function swap(nums, pos1,pos2) { var a = nums[pos1]; nums[pos1] = nums[pos2]; nums[pos2] = a; } function shuffle(nums) { for (var i = 0; i < 1000; i++) { var num1 = Math.floor((Math.random())*26); var num2 = Math.floor((Math.random())*26); swap(nums,num1,num2); } } var counter1 = 0; var counter2 = 1; function drawIt(nums) { if (nums[counter1] > nums[counter2]) { swap(nums, counter1,counter2); } var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); for (var i = 0; i < nums.length; i++) { var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); ctx.beginPath(); ctx.lineWidth = "1"; ctx.strokeStyle = "rgba(" + nums[i] + ", " + nums[i] + ", " + nums[i] + ", 1)"; ctx.rect(10, i * 15 + 10, 50, 15); ctx.stroke(); ctx.beginPath(); ctx.rect(10, i * 15 + 10, 50, 15); ctx.stroke(); ctx.fillStyle = "rgba(" + nums[i] + ", " + nums[i] + ", " + nums[i] + ", 1)"; ctx.fill(); } if (counter2 < nums.length) { counter2++; } else { counter1++; counter2 = counter1+1; } } var nums = new Array(); for (var i = 0; i<=250; i+=5) { nums[i/5] = i; } shuffle(nums); drawIt(nums); for (var i = 0; i < (nums.length*(nums.length-1)) / 2; i++) { setTimeout(drawIt(nums), 2000); } </script> </body> </html>
Unfortunately there is no way to force a draw, or DOM update, while your thread is still running. The way to solve this is to make your sort algorithm re entrant, so that it can be called from a timer, or via setTimeout. Each time the timer is triggered, you perform one iteration of the sort, and then draw the result. This is a bit annoying sometimes when studying algorithms by visualizing them, as step visualization cannot be achieved without modifying the algorithm. EDIT: Added working code snippet that implements a "reentrant" sort. <html> <body> <canvas id="myCanvas" width="300" height="700" style="border:1px solid #d3d3d3;"> </canvas> <script> function swap(nums, pos1,pos2) { var a = nums[pos1]; nums[pos1] = nums[pos2]; nums[pos2] = a; } function shuffle(nums) { for (var i = 0; i < 1000; i++) { var num1 = Math.floor((Math.random())*26); var num2 = Math.floor((Math.random())*26); swap(nums,num1,num2); } } function sleep(seconds) { var e = new Date().getTime() + (seconds * 1000); while (new Date().getTime() <= e) {} } function drawIt(nums) { var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); for (var i = 0; i < nums.length; i++) { var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); ctx.beginPath(); ctx.rect(10, i * 20 + 10, 50, 20); ctx.stroke(); ctx.fillStyle = "rgba(" + nums[i] + ", " + nums[i] + ", " + nums[i] + ", 1)"; ctx.fill(); } } var nums = new Array(); for (var i = 0; i<=250; i+=10) { nums[i/10] = i; } shuffle(nums); function sort() { var i=0; var j=0; var sortComplete=false; var reentrantSort = function() { if (nums[i] > nums[j]){ swap(nums, i, j); drawIt(nums) } j++; if (j == nums.length){ j=0;i++; if (i == nums.length ) { i=0;j=0; sortComplete=true; //Sorting is done } } if (!sortComplete){ // If sort still not complete setTimeout(reentrantSort,40); // Run next iteration in 40 ms. } }; reentrantSort(); } sort(); </script> </body> </html>
Ideally you want to separate concerns - i.e. sorting an array and rendering it's state at a given point are different problems - you could achieve this with an ES2015 generator. In the following example I've taken a generic bubble sort function and added the function* signature and a yield statement - without modifying the algorithm this effectively allows you to step through each iteration in sequence. function* bubbleSequence(arr){ for(let i = 0; i < arr.length; ++i) for(let j = 0, end = arr.length - i; j < end; ++j) if(arr[j] > arr[j+1]){ let temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; yield j+1; // <--- pauses execution } } function draw(arr, swapIdx){ let ctx = document.getElementById('my-canvas').getContext('2d'); arr.forEach((n, i) => { ctx.beginPath(); ctx.rect(i * 11 + 10, 10, 10, 40); ctx.fillStyle = `rgba(${n},${n},${n},1)`; ctx.fill(); ctx.beginPath(); ctx.moveTo(i * 11 + 10, 53); ctx.lineTo(i * 11 + 20, 53); ctx.lineWidth = 2; ctx.strokeStyle = i === swapIdx || (i+1) === swapIdx ? '#f00' : '#333'; ctx.stroke(); }); } var nums = [...Array(51)].map((_, i) => i * 5) .sort(_ => (Math.random() * 3 | 0) - 1); var sorter = bubbleSequence(nums); var interval = setInterval(_ => { let next = sorter.next(); if(next.done) clearInterval(interval); window.requestAnimationFrame(_ => draw(nums, next.value)); }, 80); <canvas id="my-canvas" width=600 height=180></canvas>
How to use pixi.js onmouseout event to scale the object from 1.x back to 1
As mentioned in the title, I want onmouseover event of an object to scale it to 1.2 of its size, and then on onmouseout event I want it to scale back to its original size (1). But the onmouseout event does not return to its original size. Related code is as follows: var renderer = PIXI.autoDetectRenderer(800, 500, { backgroundColor: 0x1099bb }); $("#container").append(renderer.view); var stage = new PIXI.Container(); var container = new PIXI.Container(); stage.addChild(container); var bunnyArray = new Array(); for (var i = 0; i < 5; i++) { bunnyArray[i] = new Array(); } for (var i = 0; i < 5; i++) { for (var j = 0; j < 5; j++) { var rect = new PIXI.Graphics(); var width = 70; rect.lineStyle(1, randomColor()); rect.interactive = true; rect.hitArea = new PIXI.Rectangle(width*i,width*j, width + width * rect.scale.x, width + width * rect.scale.y); //rect.position.x =10; //rect.position.y = 10; rect.position.set(width * i, width * j); rect.zIndex = 2; rect.drawRect(0, 0, width, width); bunnyArray[i][j] = rect; container.addChild(bunnyArray[i][j]); } } for (var i = 0; i < bunnyArray.length; i++) { for (var j = 0; j < bunnyArray[i].length; j++) { bunnyArray[i][j].on("click", onClick); bunnyArray[i][j].on("mouseover", onMouseover); bunnyArray[i][j].on("mouseout", onMouseout); } } container.x = 200; container.y = 60; renderImage(); function renderImage() { requestAnimationFrame(renderImage); //renderer.render(container); renderer.render(container); //renderer.render(stage); } function animate() { requestAnimationFrame(animate); var bunny1 = thisPointer; bunny1.rotation += 0.03; cancelAnimationFrame(request); } function Scale(pointer) { pointer.scale.x += 0.2; pointer.scale.y += 0.2; pointer.zIndex = 4; return pointer; } function ScaleDel(requestPointer) { //pointer.scale.x -= 0.2; //pointer.scale.y -= 0.2; if (requestPointer != undefined || requestPointer != null) { requestPointer.mouseover = null; } } var thisPointer; var request; function onClick(eventData) { thisPointer = calcuatePos(eventData); request = requestAnimationFrame(animate); thisPointer.rotation = 0; } var requestPointer; function onMouseover(eventData) { var thisPointer = calcuatePos(eventData); //request = requestAnimationFrame(Scale); requestPointer= Scale(thisPointer); } function onMouseout(eventData) { ScaleDel(requestPointer); } //生成随机颜色 function randomColor() { var colorStr = Math.floor(Math.random() * 0xFFFFFF).toString(16).toUpperCase(); return "000000".substring(0, 6 - colorStr) + colorStr; } //判断是否点击了这个东西 function calcuatePos(eve) { var x = (eve.data.global.x); var y = (eve.data.global.y); x =x- container.x; y =y- container.y; var increaseRectScale = 70; for (var i = 0; i < bunnyArray.length; i++) { for (var j = 0; j < bunnyArray[i].length; j++) { var instance = bunnyArray[i][j]; //increaseRectScale *= instance.scale.x; if (instance.position.x <= x && instance.position.x + increaseRectScale >= x && instance.position.y <= y && instance.position.y + increaseRectScale >= y) { //instance.pivot.set(increaseRectScale/2 , increaseRectScale/2 ); var a = document.createElement('a'); a.href = randomLink(); a.target = '_blank'; a.style.visibility = "hidden"; document.body.appendChild(a); a.click(); return instance; } } } } container.updateLayersOrder = function () { container.children.sort(function (a, b) { a.zIndex = a.zIndex || 0; b.zIndex = b.zIndex || 0; return b.zIndex - a.zIndex; }); } function randomNumber() { return Math.ceil(Math.random() * 10); } function randomLink() { var hyperLink = ""; var number = randomNumber(); switch (number) { case 0: hyperLink = "http://www.baidu.com"; break; case 1: hyperLink = "http://www.17173.com"; break; case 2: hyperLink = "http://www.stackoverflow.com"; break; case 3: hyperLink = "http://www.163.com"; break; case 4: hyperLink = "http://www.5173.com"; break; case 5: hyperLink = "http://www.sina.com"; break; case 6: hyperLink = "http://www.qq.com"; break; case 7: hyperLink = "http://www.hp.com"; break; case 8: hyperLink = "http://www.youku.com"; break; case 9: hyperLink = "http://www.tudou.com"; break; } return hyperLink; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script src="http://files.cnblogs.com/files/kmsfan/pixi.js"></script> <div id="container"></div>
You used "+=" for scaling up the Rect and, as Goose Ninja noted, you didn't scaled down in the ScaleDel function. If you want a scale factor of 1.2 just set to this scale. Turns out you don't need the function calculatePos for detecting the target object, since PIXI binds the this to them in the interactive callbacks - http://www.goodboydigital.com/pixi-js-now-even-better-at-being-interactive/ Here is a codepen: http://codepen.io/anon/pen/qOXKEZ. I just changed the onMouseOver and noMouseOut functions and set the hitArea of each object to a local rectangle: new PIXI.Rectangle(0,0, width,width) function onMouseover(eventData) { //var thisPointer = calcuatePos(eventData); //request = requestAnimationFrame(Scale); //requestPointer= Scale(thisPointer); this.scale.set(1.2,1.2); } function onMouseout(eventData) { //ScaleDel(calcuatePos(eventData)); this.scale.set(1.0,1.0); }
javascript: Getting object is not defined
when trying to reference an object created in a different function I get 'object is not defined' error. This sounds like a scope problem except this has worked in a different program before.. Error I get is 'uncaught reference error: man is not defined'.. Part of my code is listed below: Please see where the man object is created in the buildMap() function and where I try to reference it in the playGame() function.. var canvas = document.querySelector("canvas"); var drawingSurface = canvas.getContext("2d"); var man; // Map code var EMPTY = 0; var TREE_BOTTOM = 1; var TREE_TOP = 2; var SKY = 3; var CLOUD = 4; var CLOUD_LEFT = 5; var CLOUD_RIGHT = 6; var PLATFORM = 7; var EGG = 8; var CAVE = 9; var MEAT = 10; var MAN = 11; var DINO = 12; var GUARD = 13; var GROUND = 14; // Map array var map = [ [3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3], [3,3,3,3,3,3,3,3,5,6,3,3,3,3,3,3,3,3,3,3,5,6,3,3], [3,3,5,6,3,3,4,3,3,3,3,3,3,3,5,6,3,3,3,3,3,3,3,3], [3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,9,3,3,3], [3,7,7,3,3,3,3,3,3,3,3,3,3,3,3,3,7,7,7,7,7,7,3,3], [3,3,3,3,3,3,3,3,3,7,3,3,3,3,3,3,3,3,3,3,3,3,3,3], [3,3,3,7,7,7,3,3,3,3,3,3,7,7,3,3,3,3,3,3,3,4,3,3], [3,3,3,3,3,3,3,3,5,6,3,3,3,3,3,3,3,3,3,3,3,3,3,3], [3,3,4,3,3,3,3,3,3,3,3,3,4,3,3,7,7,7,7,7,3,3,3,3], [3,3,3,3,3,7,7,7,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3], [3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,3,3,3], [3,3,3,3,3,3,3,3,3,3,3,7,7,7,7,3,3,3,3,3,3,3,3,3], [3,3,2,3,3,3,3,3,3,3,2,3,3,3,3,3,2,3,3,3,2,3,3,3], [14,14,1,14,14,14,14,14,14,14,1,14,14,14,14,14,1,14,14,14,1,14,14,14] ]; var gameObjects = [ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,13,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,12,0,0,0,0,0,0,0,8,12,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,12,0,8,0,0,0,0], [0,0,0,0,0,10,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,11,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] ]; // Cell size var SIZE = 32; // The number of rows and columns var ROWS = map.length; var COLS = map[0].length; // Sprite object var spriteObject = { sourceX: 0, sourceY: 0, sourceWidth: 32, sourceHeight: 32, width: 32, height: 32, x: 0, y: 0, vx: 0, vy: 0, visible: true, //Getters centerX: function() { return this.x + (this.width / 2); }, centerY: function() { return this.y + (this.height / 2); }, halfWidth: function() { return this.width / 2; }, halfHeight: function() { return this.height / 2; }, }; //arrays to store game objects var sprites = []; var eggs = []; var dinos = []; var platforms = []; var assetsToLoad = []; var assetsLoaded = 0; //load the tilesheet var image = new Image(); image.addEventListener("load", loadHandler, false); image.src = "../images/spritesheet.png"; assetsToLoad.push(image); //Game states var LOADING = 0; var BUILD_MAP = 1; var PLAYING = 2; var OVER = 3; var gameState = LOADING; // key codes var LEFT = 37; var RIGHT = 39; var SPACE = 32; // Directions var moveLeft = false; var moveRight = false; window.addEventListener("keydown", function(event) { switch(event.keyCode) { case LEFT: moveLeft = true; break; case RIGHT: moveRight = true; break; }}, false); window.addEventListener("keyup", function(event) { switch(event.keyCode) { case LEFT: moveLeft = false; break; case RIGHT: moveRight = false; break; }}, false); update(); function update() { requestAnimationFrame(update, canvas); switch (gameState) { case LOADING: console.log("loading..."); break; case BUILD_MAP: buildMap(map); buildMap(gameObjects); gameState = PLAYING; break; case PLAYING: playGame(); break; case OVER: endGame(); break; } render(); } function loadHandler() { assetsLoaded++; if (assetsLoaded === assetsToLoad.length) { image.removeEventListener("load", loadHandler, false); gameState = BUILD_MAP; } } function buildMap(map) { for (var row=0; row < ROWS; row++) { for (var col=0; col < COLS; col++) { var currentTile = map[row] [col]; if (currentTile !== EMPTY) { switch (currentTile) { case GROUND: var ground = Object.create(spriteObject); ground.sourceX = 0; ground.sourceY = 0; ground.x = col * SIZE; ground.y = row * SIZE; sprites.push(ground); break; case TREE_BOTTOM: var treeBottom = Object.create(spriteObject); treeBottom.sourceX = 0; treeBottom.sourceY = 32; treeBottom.x = col * SIZE; treeBottom.y = row * SIZE; sprites.push(treeBottom); break; case TREE_TOP: var treeTop = Object.create(spriteObject); treeTop.sourceX = 0; treeTop.sourceY = 64; treeTop.x = col * SIZE; treeTop.y = row * SIZE; sprites.push(treeTop); break; case SKY: var sky = Object.create(spriteObject); sky.sourceX = 0; sky.sourceY = 96; sky.x = col * SIZE; sky.y = row * SIZE; sprites.push(sky); break; case CLOUD: var cloud = Object.create(spriteObject); cloud.sourceX = 0; cloud.sourceY = 128; cloud.x = col * SIZE; cloud.y = row * SIZE; sprites.push(cloud); break; case CLOUD_LEFT: var cloudLeft = Object.create(spriteObject); cloudLeft.sourceX = 0; cloudLeft.sourceY = 160; cloudLeft.x = col * SIZE; cloudLeft.y = row * SIZE; sprites.push(cloudLeft); break; case CLOUD_RIGHT: var cloudRight = Object.create(spriteObject); cloudRight.sourceX = 0; cloudRight.sourceY = 192; cloudRight.x = col * SIZE; cloudRight.y = row * SIZE; sprites.push(cloudRight); break; case PLATFORM: var platform = Object.create(spriteObject); platform.sourceX = 0; platform.sourceY = 224; platform.x = col * SIZE; platform.y = row * SIZE; sprites.push(platform); platforms.push(platform); break; case CAVE: var cave = Object.create(spriteObject); cave.sourceX = 0; cave.sourceY = 288; cave.x = col * SIZE; cave.y = row * SIZE; sprites.push(cave); break; case EGG: var egg = Object.create(spriteObject); egg.sourceX = 0; egg.sourceY = 256; egg.x = col * SIZE; egg.y = row * SIZE; sprites.push(egg); eggs.push(egg); break; case MEAT: var meat = Object.create(spriteObject); meat.sourceX = 0; meat.sourceY = 320; meat.x = col * SIZE; meat.y = row * SIZE; meat.visible = false; sprites.push(meat); break; case DINO: var dino = Object.create(spriteObject); dino.sourceX = 0; dino.sourceY = 416; dino.x = col * SIZE; dino.y = row * SIZE; sprites.push(dino); dinos.push(dino); break; case GUARD: var guard = Object.create(spriteObject); guard.sourceX = 0; guard.sourceY = 480; guard.x = col * SIZE; guard.y = row * SIZE; sprites.push(guard); break; case MAN: var man = Object.create(spriteObject); man.sourceX = 0; man.sourceY = 352; man.x = col * SIZE; man.y = row * SIZE; sprites.push(man); break; } } } } } function playGame() { if (moveLeft && !moveRight) { man.vx = -3; } if (moveRight && !moveLeft) { man.vx = 3; } if (!moveLeft && !moveRight) { man.vx = 0; } man.x += man.vx; } function endGame() { } function render() { drawingSurface.clearRect(0, 0, canvas.width, canvas.height); if (sprites.length !== 0) { for (i=0; i < sprites.length; i++) { var sprite = sprites[i]; if (sprite.visible) { drawingSurface.drawImage ( image, sprite.sourceX, sprite.sourceY, sprite.sourceWidth, sprite.sourceHeight, Math.floor(sprite.x), Math.floor(sprite.y), sprite.width, sprite.height ); } } } }
That's because man is in a local scope. Therefore, the playGame function can't "see" it. To fix this, just declare the variable (put "var man;") outside of the buildMap function (right before it, preferrably).
what i think looking at your code is .... you have declared the variable "man" which is local to function "buildMap" and you are trying to access it in another function ie. "playGame".. may be this is the problem ... you can solve it by making it global... at the topmost line of the script hope it works.