XMLHttpRequest causing strange bug in JavaScript title game - javascript

I'm writing a tile game in JS and am loading a text based map with a XMLHttpRequest object. All works well until I actually try to draw the background. The map gets initialized, but it doesn't seem to be "fully" initialized by the time I try to loop through the rows. When I try to call map[rowNum].length I get an undefined error. In the debugger, I can see that once the code jumping back to loadMapHttp() which is where the XMLHttpRequest object is defined. I don't understand why it's doing this.
var map =[];
var tiles =[];
var background = new Image();
var canvas = document.getElementById("canvas");
var graphicsContext = canvas.getContext('2d');
background.src = "imgs/tileSheet.jpg";
function loadMapHttp() {
var conn = new XMLHttpRequest();
conn.onreadystatechange = handleStateChange;
conn.open("GET","map.txt",true);
conn.send();
function handleStateChange() {
if(conn.readyState === 4){
loadMap2(conn.status == 200 ? conn.responseText : null);
}
}
}
function loadMap2(text) {
if(text == null){
console.warn("Http Error");
return;
}
console.log("text received was: " + text);
var testMap = text;
var rows = testMap.split("\n");
for(var rowNum =0; rowNum < rows.length; rowNum++){
rows[rowNum] = rows[rowNum].trim();
map.push([]);
var cols = rows[rowNum].split("");
console.log(cols);
for(var colNum = 0; colNum<cols.length; colNum++){
map[rowNum][colNum] = cols[colNum];
}
}
}
function prepTiles() {
var TILESET_LEFT = 0;
var TILESET_TOP = 0;
var TILE_WIDTH = 31.2;
var TILE_HEIGHT = 31.2;
var tileCanvas = document.createElement('canvas');
var tileContext = tileCanvas.getContext('2d');
//BRICK
tileContext.drawImage(background, TILESET_TOP+TILE_WIDTH*2, TILESET_TOP, TILE_WIDTH, TILE_HEIGHT, 0, 0, TILE_WIDTH, TILE_HEIGHT);
tiles.push(tileContext.getImageData(0, 0, TILE_WIDTH, TILE_HEIGHT));
//DIRT
tileContext.drawImage(background, TILESET_LEFT+TILE_WIDTH*17, TILESET_TOP+TILE_HEIGHT*6, TILE_WIDTH, TILE_HEIGHT, 0, 0, TILE_WIDTH, TILE_HEIGHT);
tiles.push(tileContext.getImageData(0, 0, TILE_WIDTH, TILE_HEIGHT));
//GRASS
tileContext.drawImage(background, TILESET_LEFT+TILE_WIDTH*6, TILESET_TOP+TILE_HEIGHT*12, TILE_WIDTH, TILE_HEIGHT, 0, 0, TILE_WIDTH, TILE_HEIGHT);
tiles.push(tileContext.getImageData(0, 0, TILE_WIDTH, TILE_HEIGHT));
}
function getTile(char) {
if(char == 'B'){
return tiles[0];
}
if(char == 'D'){
return tiles[1];
}
if(char == 'G'){
return tiles[2];
}
}
function drawBackground(){
for(var rowNum=0; rowNum < 6; rowNum++){
console.log(map[rowNum]);
for(var colNum=0; colNum < map[rowNum].length; colNum++){
var tile = getTile(map[rowNum][colNum]);
graphicsContext.putImageData(tile, colNum*31, rowNum*31);
}
}
}
function startGame() {
loadMapHttp();
prepTiles();
drawBackground();
}
startGame();

Related

PaperJS when adding symbol to layer, children returns undefined

I'm adding symbols (some paths) to a layer and when I'm launching onFrame animation layer's children are undefined, why?
I'm trying to add children with layer.addChild(placedSymbol);, layer children length returns correctly but if I console.log the child in a for loop returns as SymbolItem #5
Here full example code:
https://codepen.io/mrk1977_02/pen/KKPXbQM?editors=0010
setUp();
view.onFrame = function(event) {
frameAnimation(event, pathA.path, layerA);
}
function setUp(){
//PATH A
pathA.path = new Path.Circle({
center: [0, 0],
radius: radius,
fillColor: 'black'
});
//pathA.path.opacity = 0;
layerA = new Layer();
var symbol = new Symbol(pathA.path);
placeSymbol(symbol, pathA, layerA);
//IMAGE
layerImg = new Layer({
children: [raster]
});
addImage(imgPack);
//PATH B
pathB.path = pathA.path.clone();
//pathB.path.opacity = 0;
layerB = new Layer();
var symbol2 = new Symbol(pathB.path);
placeSymbol(symbol2, pathB, layerB);
}
function placeSymbol(symbol, obj, layer){
//count = layer.children.length;
for (var i = 0; i < count; i++) {
// The center position is a random point in the view:
var center = Point.random() * view.size;
var randomX = Math.sin(90*i)+view.size.width/2;
var randomY = view.size.height/count*i+radius;
var placedSymbol = symbol.place(new Point(randomX,randomY));
//placedSymbol.scale(i / count);
obj.symbolsArray.push(symbol);
obj.dotsPosXArray.push(randomX);
layer.addChild(placedSymbol);
}
}
function frameAnimation(event, path, layer){
//layer.activate();
count = layer.children.length;
for (var i = 0; i < count; i++) {
var item = layer.children[i];
console.log('item:'+item);
if(item.name != 'packaging'){
var sinus = Math.sin(event.time*Math.PI*.65 + i);
//var sinus = Math.sin(event.time + curve + i);
//Position X
path.dotsPosXArray[i] = item.position.x;
item.position.x += sinus * 2;
path.dotsPrevDirectionsArray[i] = path.dotsDirectionsArray[i];
if(item.position.x < path.dotsPosXArray[i]){
path.dotsDirectionsArray[i] = 'neg';
item.opacity = 1;
if(path.dotsPrevDirectionsArray[i] != path.dotsDirectionsArray[i]){
//item.bringToFront();
}
}else if(item.position.x > path.dotsPosXArray[i]){
path.dotsDirectionsArray[i] = 'pos';
item.opacity = 1;
if(path.dotsPrevDirectionsArray[i] != path.dotsPrevDirectionsArray[i]){
//item.sendToBack();
}
}
if(i==1){
//console.log(item.position.x);
}
//Position Y
item.position.y += (item.bounds.height / 15) +.3;
if (item.bounds.top > view.size.height) {
item.position.y = -item.bounds.height;
}
}
}
}

Colour in rendered object instance not correct and i have absolutely no idea in the whole damn world why

all i get is a little square with rgb(0,255,255) and i want the 'r' to be proportionate to the log (betterLog is a log function(base,answer)=exponent
everything
var ln = function(g){
var n=g;
n=abs(n);
if(n>1){
n=1/n;
}
var x=n-1;
var output = x;
var i;
for(i = 2; i < 99; i++){
if (i%2 === 0){
output -= pow(x,i)/i;
}
if (i%2 === 1){
output += pow(x,i)/i;
}
}
return output;
};
var betterLog = function(a,b){
var output = ln(b)/ln(a);
return output;
};
var v=475;
var block = function(){
this.render = function(){
var stupidColor=(betterLog(2,v)*20);
fill(stupidColor, 255, 255);
rect(20,20,20,20);
};
};
var newCrap = new block();
var draw = function() {
newCrap.render(v);
};
its just a rgb(0,255,255) idk if its rendering correct5ly or not im new to js and its just not working as wanted no errors per se
You just need to add the Mathobject to your functions
var ln = function(g){
var n=g;
n=Math.abs(n);
if(n>1){
n=1/n;
}
var x=n-1;
var output = x;
var i;
for(i = 2; i < 99; i++){
if (i%2 === 0){
output -= Math.pow(x,i)/i;
}
if (i%2 === 1){
output += Math.pow(x,i)/i;
}
}
return output;
};
var betterLog = function(a,b){
var output = ln(b)/ln(a);
return output;
};
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
var fill = function(r,g,b,a){
ctx.fillStyle = 'rgba('+r+','+g+','+b+','+a||1+')';
};
var rect = function(x,y,w,h){
ctx.fillRect(x,y,w,h);
};
var v=475;
var block = function(){
this.render = function(v){
var stupidColor=(betterLog(2,v)*20);
fill(stupidColor, 255, 255);
console.log({stupidColor});
rect(20,20,20,20);
};
};
var newCrap = new block();
var draw = function() {
newCrap.render(v);
};
draw();
<canvas></canvas>

Alert showing two times

I use cordova and Framework7 for create app. My script load and show image from server fine, but if server return 404 I get alert 2 times. Why, and how can I fix it?
function view(a) {
var img = new Image();
var s = a;
myApp.showPreloader('Загружаем...');
img.src = s;
img.onload = function() {
document.getElementById('showimg').innerHTML = '';
var openPhotoSwipe = function(a) {
myApp.hidePreloader();
myApp.allowPanelOpen = false;
document.getElementById("check").style.display = "block";
var pswpElement = document.querySelectorAll('.pswp')[0];
var items = [{
src: s,
w: img.width,
h: img.height
}];
var options = {
showAnimationDuration: 0,
hideAnimationDuration: 0
};
var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options);
gallery.init();
gallery.listen('destroy', function() {
document.getElementById("check").style.display = "none";
var elements = document.getElementsByTagName("input");
for (var ii = 0; ii < elements.length; ii++) {
if (elements[ii].type == "text") {
elements[ii].value = "";
}
}
$$(window).width() < 770 && (myApp.allowPanelOpen = !0);
});
};
openPhotoSwipe();
}
img.onerror = function() {
myApp.alert('Not found...');
myApp.hidePreloader();
}}
Try this:
function view(a) {
var img = new Image();
var s = a;
myApp.showPreloader('?????????...');
img.src = s;
var alertShown = false;
img.onload = function() {
document.getElementById('showimg').innerHTML = '';
var openPhotoSwipe = function(a) {
myApp.hidePreloader();
myApp.allowPanelOpen = false;
document.getElementById("check").style.display = "block";
var pswpElement = document.querySelectorAll('.pswp')[0];
var items = [{
src: s,
w: img.width,
h: img.height
}];
var options = {
showAnimationDuration: 0,
hideAnimationDuration: 0
};
var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options);
gallery.init();
gallery.listen('destroy', function() {
document.getElementById("check").style.display = "none";
var elements = document.getElementsByTagName("input");
for (var ii = 0; ii < elements.length; ii++) {
if (elements[ii].type == "text") {
elements[ii].value = "";
}
}
$$(window).width() < 770 && (myApp.allowPanelOpen = !0);
});
};
openPhotoSwipe();
}
img.onerror = function() {
myApp.hidePreloader();
if(!alertShown){
alertShown = true;
myApp.alert('Not found...');
}
}}
}

Saving and loading canvas data from localStorage

I need to save all drawings from my canvas in order to be able to return to them later on.
I succeed in getting and putting data but I can't save the object and return it correctly.
This is my code:
var imgData = a.getImageData(0, 0, 500, 200);
localStorage.setItem("test",JSON.stringify(imgData))
console.log(imgData)
console.log(JSON.parse(localStorage.getItem("test")))
b.putImageData(imgData, 0, 0);
You can use the canvas.toDataURL() method which will encode the canvas into Base64.
You can then create a image with the source being the data url and then draw that image to the canvas.
Here is the working sample.
var canvas = document.getElementById('tutorial');
var ctx = canvas.getContext('2d');
var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgb(200,0,0)";
ctx.fillRect (10, 10, 55, 50);
var url = canvas.toDataURL();
localStorage.setItem('url', url);
var canvas2 = document.getElementById('tutorial2');
var ctx2 = canvas2.getContext("2d");
var toDrawUrl = localStorage.getItem('url');
drawDataURIOnCanvas(toDrawUrl, ctx2);
ctx2.fillStyle = "rgb(200,200,0)";
ctx2.fillRect (20, 20, 55, 50);
function drawDataURIOnCanvas(strDataURI, context) {
"use strict";
var img = new window.Image();
img.addEventListener("load", function () {
context.drawImage(img, 0, 0);
});
img.setAttribute("src", strDataURI);
}
i want to save the huge data as imagedate in local-storage you must be convert from buffer to string and used this functions
function buf2str(buf) {
var bufView = new Uint16Array(buf);
var unis =""
for (var i = 0; i < bufView.length; i++) {
unis=unis+String.fromCharCode(bufView[i]);
}
return unis
}
to reverse function use this function
function str2buf(str) {
var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
var bufView = new Uint16Array(buf);
for (var i=0, strLen=str.length; i<strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
i has success to save data and edit it after callback
my code is
var canvasData={
_save:function(from,id){
var imgData = from.getImageData(0, 0, el.width, el.height);
var buffer = imgData.data.buffer;
var testV=ab2str(buffer);
try {
localStorage.setItem(id+"Length",testV._length)
localStorage.setItem(id+"Keys",testV._keys)
localStorage.setItem(id+"Data",testV._Data)
} catch(e) {
var storageSize = Math.round(JSON.stringify(localStorage).length / 1024);
console.log("LIMIT REACHED: (" + i + ") " + storageSize + "K");
console.log(e);
alert("your localStorage is complete , you must delete some nots or markers to be can store again ")
}
},
_return:function(to,id){
var tempObj={_Length:0,_Keys:"",_Data:""}
try {
tempObj._Length= localStorage.getItem(id+"Length")
tempObj._Keys= localStorage.getItem(id+"Keys")
tempObj._Data= localStorage.getItem(id+"Data")
} catch(e) {
var storageSize = Math.round(JSON.stringify(localStorage).length / 1024);
console.log("LIMIT REACHED: (" + i + ") " + storageSize + "K");
console.log(e);
}
if (tempObj ==null ){return false};
if (tempObj._Length ==null ){return false};
if (tempObj._Keys ==null ){return false};
if (tempObj._Data ==null ){return false};
var temp=tempObj._Length.split(",");
var newWidth=parseInt(temp[0]);
var newHeight= parseInt(temp[1]);
var newImgData = to.createImageData(newWidth,newHeight);
var incomingBuffer=returnOriginalBuffer(tempObj)
newImgData.data.set(new Uint8Array(incomingBuffer))
to.putImageData(newImgData, 0, 0);
}
}
function ab2str(buf) {
var bufView = new Uint16Array(buf);
var dataArr=new Array();
var dataStr =""
var keysStr =""
var lenStr=el.width.toString()+","+el.height.toString()
var returnedObj={_length:lenStr,_keys:"",_Data:""}
var dote="";
for (var q = 0; q < bufView.length; q++) {
if(bufView[q]!=0){
keysStr=keysStr+dote+q;
dote=","
dataArr.push(bufView[q]);
}
}
for (var w = 0; w < dataArr.length; w++) {
dataStr=dataStr+String.fromCharCode(dataArr[w]);
}
returnedObj._keys=keysStr;
returnedObj._Data=dataStr;
return returnedObj
}
function returnOriginalBuffer(tempObj) {
var temp=tempObj._Length.split(",");
var _length=parseInt(temp[0])*parseInt(temp[1])*2
var _keys=tempObj._Keys;
var _data=tempObj._Data;
var keysArr =new Array();
var dataArr=new Array();
keysArr=_keys.split(",")
for (var w=0, strLen=_data.length; w<strLen; w++) {
dataArr[w]=_data.charCodeAt(w) ;
}
var buf = new ArrayBuffer(_length*2); // 2 bytes for each char
var bufView = new Uint16Array(buf);
var q=0
for (var i=0, strLen=_length; i<strLen; i++) {
if (i!=parseInt(keysArr[q])){
bufView[i] = 0;
}else{
bufView[i] = dataArr[q]
q++;
}
}
return buf;
}
//save data
canvasData._save(ctx,"localstoragename")
// return data
canvasData._return(ctx,"localstoragename")
this soluation is complex if any one own simple workaround, help us

why will lines 56 and 67 not work? (.votess +=1;)

var imgs = ['bmw.jpg', 'bugatti.jpg', 'classic.jpg', 'concept.jpg', 'corvette.jpg', 'dino.jpg', 'lambo.jpg', 'mcclaren.jpg', 'p1.jpg', 'porsche.jpg', 'rally.jpg', 'audi.jpg'];
// var imgs_count = {'bmw.jpg': 0, 'bugatti.jpg': 0, 'classic.jpg': 0, 'concept.jpg': 0, 'corvette.jpg': 0, 'dino.jpg': 0, 'lambo.jpg': 0, 'mcclaren.jpg': 0, 'p1.jpg': 0, 'porsche.jpg': 0,'rally.jpg': 0, 'audi.jpg':0}
// for (var i in imgs_count) {
// imgs_count[i]
// }
var allCars = [];
var votes;
function Car(file) {
this.file = file;
this.votes = 0;
allCars.push(this);
}
var bmw = new Car('bmw.jpg');
var bugatti = new Car('bugatti.jpg');
var classic = new Car('classic.jpg');
var concept = new Car('concept.jpg');
var corvette = new Car('corvette.jpg');
var dino = new Car('dino.jpg');
var lambo = new Car('lambo.jpg');
var mcclaren = new Car('mcclaren.jpg');
var p1 = new Car('p1.jpg');
var porsche =new Car('porsche.jpg');
var rally = new Car('rally.jpg');
var audi = new Car('audi.jpg');
var idx1 = 0;
var idx2 = 0;
var path = 'cars/';
var done = false;
function getRandomImage() {
idx1 = Math.floor(Math.random()*imgs.length);
var img1 = imgs[idx1];
idx2 = idx1;
while (idx2 == idx1) {
idx2 = Math.floor(Math.random()*imgs.length);
}
img2 = imgs[idx2];
document.getElementById('choice1').setAttribute('src', path + img1);
document.getElementById('choice2').setAttribute('src', path + img2);
}
function setOnClicks(id) {
document.getElementById(id).addEventListener('click', function(event) {
var choice = event.target.id;
if (choice === 'choice1') {
console.log(allCars);
var img = document.getElementById(id).getAttribute('src');
var allCars = img.slice(5,img.length);
this.allCars[idx1].votes += 1;
console.log(idx1);
console.log(this.allCars[idx1].votes)
if ( allCars[idx1].votes=3) {
done = true;
}
}
if (choice === 'choice2') {
var img = document.getElementById(id).getAttribute('src');
var allCars = img.slice(5,img.length);
console.log(idx2);
console.log(this.allCars[idx2].votes);
this.allCars[idx2].votes += 1;
if (allCars[idx2].votes == 3) {
done = true;
}
}
if (!done)
getRandomImage();
});
}
getRandomImage();
setOnClicks('choice1');
setOnClicks('choice2')l
You're overwriting your global allCars with a local var declaration of the same name:
var allCars = img.slice(5,img.length);
you are creating a local variable allCars under click event, while this.allCars is point to the allCars variable under window object
var allCars = img.slice(5,img.length); // this is a local variable
this.allCars[idx1].votes += 1; // this is same as window.allCars
console.log(idx1);

Categories