Alert showing two times - javascript

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...');
}
}}
}

Related

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>

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);

modify function for local HTML code

I have function that works perfect, but not for my scope:
function _svgToCanvas() {
var nodesToRecover = [];
var nodesToRemove = [];
var svgElems = document.getElementsByTagName('svg');
for (var i = 0; i < svgElems.length; i++) {
var node = svgElems[i];
var parentNode = node.parentNode;
var svg = parentNode.innerHTML;
var canvas = document.createElement('canvas');
canvg(canvas, svg);
nodesToRecover.push({
parent: parentNode,
child: node
});
parentNode.removeChild(node);
nodesToRemove.push({
parent: parentNode,
child: canvas
});
parentNode.appendChild(canvas);
}
}
I'm trying to modify it for using local code that comes from param, like this:
function _svgToCanvas(content) {
var nodesToRecover = [];
var nodesToRemove = [];
var svgElems = content.getElementsByTagName('svg');
for (var i = 0; i < svgElems.length; i++) {
}
return content;
}
var content = $('#main_contents').get(0);
result = _svgToCanvas(content);
But I can't modify the for loop. How to modify it?
Looks like the "var svg = parentNode.innerHTML;" doesn't give you the correct parameter for function canvg.
This piece of code comes from canvg.js, try it.
function _svgToCanvas(content) {
var svgTags = content.querySelectorAll('svg');
for (var i=0; i<svgTags.length; i++) {
var svgTag = svgTags[i];
var c = document.createElement('canvas');
c.width = svgTag.clientWidth;
c.height = svgTag.clientHeight;
svgTag.parentNode.insertBefore(c, svgTag);
svgTag.parentNode.removeChild(svgTag);
var div = document.createElement('div');
div.appendChild(svgTag);
canvg(c, div.innerHTML);
}
return content;
}
This funtion will not change the original content, and just return a new dom node.
function _svgToCanvas(content) {
var newContent = content.cloneNode(true);
var svgTags = newContent.querySelectorAll('svg');
var svgTagsOriginal = content.querySelectorAll('svg');
for (var i=0; i<svgTags.length; i++) {
var svgTag = svgTags[i];
var svgTagOriginal = svgTagsOriginal[i];
var c = document.createElement('canvas');
c.width = svgTagOriginal.clientWidth;
c.height = svgTagOriginal.clientHeight;
svgTag.parentNode.insertBefore(c, svgTag);
svgTag.parentNode.removeChild(svgTag);
content.appendChild(c);
var div = document.createElement('div');
div.appendChild(svgTag);
canvg(c, div.innerHTML);
}
return newContent;
}

Dynamically playing multiple sounds using javascript

var actions = function(){return {whichPattern:"pattern1"}};
var audio = new Audio();
var _play = function(){
var l = pattern[actions().whichPattern].instrument.length,
times_played =0;
var p = setInterval(function(){
var x = pattern[actions().whichPattern][times_played];
for(var i=0; i<x.length;i++){
var toBePlayed = pattern[actions().whichPattern][times_played][i],
url= "All Drums sounds/"+toBePlayed+".wav";
audio.src = url;
audio.play();
console.log(audio);
times_played++;
}
}, pattern_config[actions().whichPattern].delay);
if(times_played === l){
clearInterval(p);
};
var pp=document.getElementById("play_pause");
pp.style.background="url('graphics/pause.png') no-repeat";
pp.style.backgroundSize ="30px 28px"
audio.source='All Drums sounds/'+pattern['pattern1'][1][0]+'.wav';
audio.play();
};
var pattern_config = {
pattern1:{
WP_slotsCounter:0,
instrument:["Kick_02", "F_T_03", "Rude_cymbal_02"],
delay:10
},
};
var pattern={
pattern1: [], // [['asas', 'sf', 'asd'], ['svv','dgh','sdgh']]
}
The above code is very simple. The first function return an object ...
well the main motive of mine is like :
assuming that pattern.pattern1 = [['asas', 'sf', 'asd'], ['svv','dgh','sdgh']] so i what that the all the strings in the pattern['pattern1'][0] should play at same instant and then with a delay of patter_config[actions().whichPattern].delay that sound files with that names of pattern['pattern1'][1] should play together.
so to achieve this i made the above function _play()
well the problem is that it is not playing the music files and not giving any errors too so that i can identify where is that problem.
pattern["pattern1"] is an array of strings and does not have any 'instrument' property
maybe you were trying to use pattern_config["pattern1"]
var actions = function () {
return {
whichPattern: "pattern1"
}
};
var audio = new Audio();
var _play = function () {
var l = pattern_config[actions().whichPattern].instrument.length,
times_played = 0;
var p = setInterval(function () {
var x = pattern_config[actions().whichPattern][times_played];
for (var i = 0; i < x.length; i++) {
var toBePlayed = pattern_config[actions().whichPattern][times_played][i],
url = "All Drums sounds/" + toBePlayed + ".wav";
audio.src = url;
audio.play();
console.log(audio);
times_played++;
}
}, pattern_config[actions().whichPattern].delay);
if (times_played === l) {
clearInterval(p);
};
var pp = document.getElementById("play_pause");
pp.style.background = "url('graphics/pause.png') no-repeat";
pp.style.backgroundSize = "30px 28px"
audio.source = 'All Drums sounds/' + pattern['pattern1'][1][0] + '.wav';
audio.play();
};
var pattern_config = {
pattern1: {
WP_slotsCounter: 0,
instrument: ["Kick_02", "F_T_03", "Rude_cymbal_02"],
delay: 10
},
};
var pattern = {
pattern1: [['asas', 'sf', 'asd'], ['svv','dgh','sdgh']],
}

Categories