Moving images with the same function called multiple times - javascript

What i want to do is a screensaver thing, like some image moving and bouncing off the sides of the screen, changing direction. It works perfectly with one image, however after i rewrote it to function with any number of images bouncing, there was following issue: The images always group up and then move completely alike. Here is a the code and a fiddle:
HTML:
<div id="blackscreen">
<img src="https://cdn.pixabay.com/photo/2016/08/12/04/03/mask-1587566_960_720.png" style="top: 0%; left: 0%;">
<img src="https://cdn.pixabay.com/photo/2016/08/12/04/03/mask-1587566_960_720.png" style="top: 0%; left: 80%;">
<img src="https://cdn.pixabay.com/photo/2016/08/12/04/03/mask-1587566_960_720.png" style="top: 0%; left: 50%;">
<img src="https://cdn.pixabay.com/photo/2016/08/12/04/03/mask-1587566_960_720.png" style="top: 0%; left: 20%;">
</div>
CSS:
img {
width: 15vw;
position: absolute;
left: 42%;
top: 0%;
}
JS:
var mousemoving = false;
var c = 0;
var stop = false;
var ssr = false;
window.mov = [];
window.uparr = [];
window.rightarr = [];
window.vcarr = [];
window.hcarr = [];
screensaver();
function screensaver() {
if(ssr) {return;}
ssr = true;
var b = document.getElementById('blackscreen');
var body = document.getElementsByTagName('body')[0];
var check = setInterval(function() {
if(c<10) {
if (mousemoving) {
mousemoving = false;
c=0;
}
else {
c++;
console.log(c);
}
b.style.display = "none";
body.style.overflow = "auto";
}
else {
body.style.overflow = "hidden";
b.style.display = "block";
stop = false;
clearInterval(check);
mov = b.getElementsByTagName('img');
uparr = [];
rightarr = [];
for (var i = 0; i < mov.length; i++) {
uparr[i] = false;
rightarr[i] = false;
vcarr[i] = 0;
hcarr[i] = 0;
}
mtv(0);
mth(0);
var i = 1;
var move = setInterval(function() {
if(i>=mov.length) {
clearInterval(move);
return;
}
mtv(i);
mth(i);
i++;
},1)
}
},100)
ssr = false;
}
function mtv(index) {
var item = mov[index];
var posy = 0;
var togoy = 0;
var up = uparr[index];
var vc = vcarr[index];
if(up) {
posy = Number(item.style.top.replace("%",""));
togoy = -posy;
}
else {
posy = Number(item.style.top.replace("%",""));
togoy = 70 - posy;
}
var perticky = togoy / 100;
var v = setInterval(function() {
if(stop) {
clearInterval(v);
c = 0;
var b = document.getElementById('blackscreen');
var body = document.getElementsByTagName('body')[0];
b.style.display = "none";
body.style.overflow = "auto";
if(index == 0) {
screensaver();
}
return;
}
if(vc>99) {
vcarr[index]=0;
clearInterval(v);
if(up) {
uparr[index] = false;
}
else {
uparr[index] = true;
}
if(stop==false) {
mtv(index);
}
return;
}
posy = Number(item.style.top.replace("%",""));
var newvaly = posy + perticky;
item.style.top = newvaly + "%";
vc++;
},17)
}
function mth(index) {
var item = mov[index];
var posx = 0;
var togox = 0;
var right = rightarr[index];
var hc = hcarr[index]
if(right) {
posx = Number(item.style.left.replace("%",""));
togox = -posx;
}
else {
posx = Number(item.style.left.replace("%",""));
togox = 82 - posx;
}
var pertickx = togox / 100;
var h = setInterval(function() {
if(stop) {
clearInterval(h);
c = 0;
return;
}
if(hc>99) {
hcarr[index]=0;
clearInterval(h);
if(right) {
rightarr[index] = false;
}
else {
rightarr[index] = true;
}
if(stop == false) {
mth(index);
}
return;
}
posx = Number(item.style.left.replace("%",""));
var newvalx = posx + pertickx;
item.style.left = newvalx + "%";
hc++;
},30)
}
https://jsfiddle.net/cwb2frmd/1/
Don't worry about c or mousemoving, they are only for the effect of the images appearing after not moving the mouse for some time.
Altough it looks quite funny as well, i would like all of the images to move autonomously. One possible reason for the error might be that a function called multiple times still shares the variables with other instances? of the function, but i didn't find any information on that. Any help is appreciated.

Related

Trying to select lines or rectangles on a canvas

I want to be able to click any line(muscle) and new line then highlight it in my program like I can do with the nodes right now. I want to use context.isPointInPath(), but I feel like that will be too limiting in the fact that the lines are only 1 pixel wide. And now I want to look at changing the lines to rectangles. Because then I would be able to just see if the mouseclick is within the rectangle height and width. But, I'm having trouble finding out a way to connect the rectangle to two nodes like I have it with the strokes right now.
My program so far:
/*jshint esversion: 6 */
//draw everything on canvas
//TODO: Change use of canvas to a container and moving elements around to avoid the buffer of frame drawing
//Node class
class Node {
constructor(x, y, r, color, highlight, highlightColor) {
this.x = x;
this.y = y;
this.r = r || 20;
this.color = color || "#ff0";
this.highlight = highlight || false;
this.highlightColor = highlightColor || "#0000FF";
}
}
//Muscle class
class Muscle {
constructor(node1, node2, width, color) {
this.node1 = node1;
this.node2 = node2;
this.width = width || 5;
this.color = color || "#f00";
//Properties of the nodes this muscle attaches to
Object.defineProperties(this, {
node1x: {
"get": () => this.node1.x,
"set": x => {
this.node1.x = x;
}
},
node1y: {
"get": () => this.node1.y,
"set": y => {
this.node1.y = y;
}
},
node2x: {
"get": () => this.node2.x,
"set": x => {
this.node2.x = x;
}
},
node2y: {
"get": () => this.node2.y,
"set": y => {
this.node2.x = y;
}
}
});
}
}
function setParentForNodes() {
this.nodes.forEach(node => {
node.parentCreature = this;
});
}
class Creature {
constructor(nodes, muscles, nodeColors) {
this.nodes = nodes;
this.muscles = muscles;
this.nodeColors = nodeColors || "#ff0";
setParentForNodes.call(this);
Object.defineProperties(this, {
creatureNumber: {
"get": () => creatures.indexOf(this),
}
});
}
addNewNode(newNode) {
newNode.parentCreature = this;
this.nodes.push(newNode);
}
addNewNodes(newNodes) {
newNodes.forEach(function(node) {
node.parentCreature = this;
}, this);
this.nodes = this.nodes.concat(newNodes);
}
}
var nodes = [
new Node(100, 100),
new Node(200, 200)
];
var muscles = [
new Muscle(nodes[0], nodes[1])
];
var creatures = [
new Creature(nodes, muscles)
];
var addNodePressed = false;
var attachMusclePressed = false;
var addLimbPressed = false;
function draw(container, ctx, nodes, creatureMuscles) {
//draw in the container
ctx.fillStyle = "#000000";
ctx.fillRect(container.y, container.x, container.width, container.height);
// for loop to draw all objects of nodes
for (let i = 0; i < creatures.length; i++) {
var creatureNodes = creatures[i].nodes;
for (let i = 0; i < creatureNodes.length; i++) {
ctx.beginPath();
ctx.arc(creatureNodes[i].x, creatureNodes[i].y, creatureNodes[i].r, 0, 2 * Math.PI);
ctx.fillStyle = creatureNodes[i].color;
ctx.closePath();
ctx.fill();
//check if node needs to be highlighted
if (creatureNodes[i].highlight == true) {
ctx.beginPath();
ctx.arc(creatureNodes[i].x, creatureNodes[i].y, creatureNodes[i].r, 0, 2 * Math.PI);
ctx.strokeStyle = creatureNodes[i].highlightColor;
ctx.lineWidth = 5; // for now
ctx.closePath();
ctx.stroke();
}
}
creatureMuscles = creatures[i].muscles;
//loop and draw every muscle
for (let i = 0; i < creatureMuscles.length; i++) {
ctx.beginPath();
ctx.moveTo(creatureMuscles[i].node1x, creatureMuscles[i].node1y);
ctx.lineTo(creatureMuscles[i].node2x, creatureMuscles[i].node2y);
ctx.strokeStyle = creatureMuscles[i].color;
ctx.lineWidth = creatureMuscles[i].width;
ctx.closePath();
ctx.stroke();
}
}
}
//Handle moving a node with mousedrag
function handleMouseDrag(canvas, creatureNodes) {
var isDrag = false;
var dragNode;
var offset = {
x: 0,
y: 0,
x0: 0,
y0: 0
};
canvas.addEventListener("mousedown", function(e) {
//mousedown then save the position in var x and y
var x = e.offsetX,
y = e.offsetY;
//loop through all the nodes to find the first node that is within radius of the mouse click
for (let i = 0; i < creatures.length; i++) {
var creatureNodes = creatures[i].nodes;
for (let i = 0; i < creatureNodes.length; i++) {
if (Math.pow(x - creatureNodes[i].x, 2) + Math.pow(y - creatureNodes[i].y, 2) < Math.pow(creatureNodes[i].r, 2)) {
isDrag = true;
dragNode = creatureNodes[i];
//offset.x&y = where the node is currently
//offset x0&y0 = where the user clicked
offset = {
x: dragNode.x,
y: dragNode.y,
x0: x,
y0: y
};
return;
}
}
}
});
// when mouse moves and isDrag is true, move the node's position
canvas.addEventListener("mousemove", function(e) {
/*when the user moves the mouse, take the difference of where his mouse is right now and where the user clicked.
Then, add that to where the node is right now to find the correct placement of the node without centering on your mouse
*/
if (isDrag) {
dragNode.x = e.offsetX - offset.x0 + offset.x; // where the mouse is right now - where the user mousedown + where the node is right now
dragNode.y = e.offsetY - offset.y0 + offset.y;
}
});
canvas.addEventListener("mouseup", function(e) {
isDrag = false;
});
canvas.addEventListener("mouseleave", function(e) {
isDrag = false;
});
}
//Handle highlighting and button functionality
function handleMouseClick(canvas, nodes, muscles) {
var highlighted;
var highlightedNode;
canvas.addEventListener("mousedown", function(e) {
var x = e.offsetX,
y = e.offsetY;
var loopbreak = false;
for (let i = 0; i < creatures.length; i++) {
var creatureNodes = creatures[i].nodes;
for (let i = 0; i < creatureNodes.length; i++) {
// check if click is within radius of a node, if it is, highlight and set highlight boolean to true.
if (Math.pow(x - creatureNodes[i].x, 2) + Math.pow(y - creatureNodes[i].y, 2) < Math.pow(creatureNodes[i].r, 2)) {
var clickedNode = creatureNodes[i];
if (addNodePressed) {
console.log("Not valid. Cannot add a node on top of another node.");
loopbreak = true;
break;
} else if (addLimbPressed) {
console.log("Not valid. Cannot add a limb on top of another node.");
loopbreak = true;
break;
} else if (attachMusclePressed) {
if (highlightedNode == clickedNode) {
console.log("Not valid. Cannot attach muscle to the same node.");
loopbreak = true;
break;
} else {
var newMuscle;
if (highlightedNode.parentCreature.creatureNumber == clickedNode.parentCreature.creatureNumber) {
newMuscle = new Muscle(highlightedNode, clickedNode);
highlightedNode.parentCreature.muscles.push(newMuscle);
attachMuscle();
highlightedNode.highlight = false;
highlighted = false;
devTools(true, false, false, false);
} else {
var newNodes = [];
var newMuscles = [];
if (highlightedNode.parentCreature.creatureNumber > clickedNode.parentCreature.creatureNumber) {
highlightedNode.parentCreature.nodes.forEach(function(node) {
newNodes.push(node);
});
highlightedNode.parentCreature.muscles.forEach(function(muscle) {
newMuscles.push(muscle);
});
newMuscle = new Muscle(highlightedNode, clickedNode);
clickedNode.parentCreature.muscles.push(newMuscle);
clickedNode.parentCreature.muscles = clickedNode.parentCreature.muscles.concat(newMuscles);
creatures.splice(creatures.indexOf(highlightedNode.parentCreature), 1);
clickedNode.parentCreature.addNewNodes(newNodes);
} else {
clickedNode.parentCreature.nodes.forEach(function(node) {
newNodes.push(node);
console.log("Clicked node is bigger.");
});
clickedNode.parentCreature.muscles.forEach(function(muscle) {
newMuscles.push(muscle);
});
newMuscle = new Muscle(highlightedNode, clickedNode);
highlightedNode.parentCreature.muscles.push(newMuscle);
highlightedNode.parentCreature.muscles = highlightedNode.parentCreature.muscles.concat(newMuscles);
creatures.splice(creatures.indexOf(clickedNode.parentCreature), 1);
highlightedNode.parentCreature.addNewNodes(newNodes);
}
highlightedNode.highlight = false;
attachMuscle();
devTools(true, false, false, false);
}
}
}
//no button pressed - highlight/unhighlight node
else {
if (highlighted || creatureNodes[i].highlight) {
if (highlightedNode != creatureNodes[i]) {
highlightedNode.highlight = false;
highlightedNode = creatureNodes[i];
highlightedNode.highlight = true;
devTools(false, true, true, true);
} else {
highlightedNode = creatureNodes[i];
highlightedNode.highlight = false;
highlighted = false;
highlightedNode = undefined;
devTools(true, false, false, false);
}
} else {
highlightedNode = creatureNodes[i];
highlightedNode.highlight = true;
highlighted = true;
devTools(false, true, true, true);
}
loopbreak = true;
break;
}
}
}
}
// if click was not in radius of any nodes then check for add limb or create node button press.
if (!loopbreak) {
loopbreak = false;
var newNode;
if (addNodePressed) {
newNode = new Node(x, y);
let newNodes = [];
let newMuscles = [];
newNodes.push(newNode);
var newCreature = new Creature(newNodes, newMuscles);
creatures.push(newCreature);
addNode();
addNodePressed = false;
devTools(true, false, false, false);
} else if (addLimbPressed) {
newNode = new Node(x, y);
let newMuscle = new Muscle(newNode, highlightedNode);
highlightedNode.parentCreature.addNewNode(newNode);
highlightedNode.parentCreature.muscles.push(newMuscle);
addLimb();
addLimbPressed = false;
highlightedNode.highlight = false;
highlighted = false;
highlightedNode = undefined;
devTools(true, false, false, false);
}
}
});
}
//Handle Devtools
function devTools(addNode, removeNode, attachMuscle, addLimb) {
var creatureNumberHTML = document.getElementById("creatureNumber");
var selectedHTML = document.getElementById("selected");
var addNodeB = document.getElementById("addNode");
var removeNodeB = document.getElementById("removeNode");
var attachMuscleB = document.getElementById("attachMuscle");
var addLimbB = document.getElementById("addLimb");
addNodeB.disabled = (addNode) ? false : true;
removeNodeB.disabled = (removeNode) ? false : true;
attachMuscleB.disabled = (attachMuscle) ? false : true;
addLimbB.disabled = (addLimb) ? false : true;
for (let i = 0; i < creatures.length; i++) {
var creatureNumber = i;
var creatureNodes = creatures[i].nodes;
for (let i = 0; i < creatureNodes.length; i++) {
if (creatureNodes[i].highlight == true) {
selectedHTML.innerHTML = `Selected: ${i} node`;
creatureNumberHTML.innerHTML = `Creature number: ${creatureNumber}`;
return;
} else {
creatureNumberHTML.innerHTML = "Creature number: -";
selectedHTML.innerHTML = "Selected: None";
}
}
}
}
//Handle add node button
function addNode() {
var addNodeB = document.getElementById("addNode");
if (addNodePressed) {
addNodePressed = false;
addNodeB.style.background = "";
} else {
addNodePressed = true;
addNodeB.style.backgroundColor = "#808080";
//and unhighlight
}
}
//Handle remove node button
function removeNode() {
for (let i = 0; i < creatures.length; i++) {
var creatureNodes = creatures[i].nodes;
var creatureMuscles = creatures[i].muscles;
for (let i = 0; i < creatureNodes.length; i++) {
if (creatureNodes[i].highlight == true) {
let highlightedNode = creatureNodes[i];
for (let i = 0; i < creatureMuscles.length; i++) {
if (creatureMuscles[i].node1 == highlightedNode || creatureMuscles[i].node2 == highlightedNode) {
creatureMuscles.splice(i, 1);
i--;
}
}
creatureNodes.splice(i, 1);
}
}
}
devTools(true, false, false, false);
}
//Handle attach muscle button
function attachMuscle() {
var attachMuscleB = document.getElementById("attachMuscle");
if (attachMusclePressed) {
attachMusclePressed = false;
attachMuscleB.style.background = "";
} else {
attachMusclePressed = true;
attachMuscleB.style.backgroundColor = "#808080";
}
}
//Handle add limb button
function addLimb() {
var addLimbB = document.getElementById("addLimb");
if (addLimbPressed) {
addLimbPressed = false;
addLimbB.style.background = "";
} else {
addLimbPressed = true;
addLimbB.style.backgroundColor = "#808080";
}
}
//Main - Grabs document elements to draw a canvas on, init node and muscle arrays and then continuously updates frame to redraw
function main() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var container = {
x: 0,
y: 0,
get width() {
return canvas.width;
},
get height() {
return canvas.height;
}
};
handleMouseDrag(canvas, nodes);
handleMouseClick(canvas, nodes, muscles);
// refresh and redraw with new properties in an updateframe infinite loop
function updateFrame() {
ctx.save();
draw(container, ctx, nodes, muscles);
ctx.restore();
requestAnimationFrame(updateFrame);
}
updateFrame();
}
main();
#canvas {
display: block;
}
#info {
display: inline-block;
text-overflow: clip;
overflow: hidden;
margin-right: 200px;
}
#commands {
display: inline-block;
text-align: center;
margin-left: 200px;
}
#devTools {
background-color: aqua;
width: 1500px;
}
section {
width: 200px;
height: 200px;
background-color: grey;
vertical-align: top;
}
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="styles.css" />
</head>
<body>
<!--TODO: Adjust the size of the canvas to fit the window-->
<canvas id="canvas" width="1500" , height="600"></canvas>
<!--TODO: Create buttons for all devtools under the canvas-->
<!--TODO: Make a container for all devtools under the canvas, then add all the functionality to it after-->
<div id="devTools">
<section id="info">
<p>Info</p>
<p id="creatureNumber">Creature Number: -</p>
<p id="selected">Selected: </p>
</section>
<section id="commands">
<p>Commands</p>
<button type="button" id="addNode" onclick="addNode()">Add node</button>
<button type="button" id="removeNode" disabled=true onclick="removeNode()">Remove node</button>
<button type="button" id="attachMuscle" disabled=true onclick="attachMuscle()">Attach muscle</button>
<button type="button" id="addLimb" disabled=true onclick="addLimb()">Add Limb</button>
<div id="muscleLength">
<button type="button" id="increaseLengthB">↑</button>
<p>Muscle Length</p>
<button type="button" id="decreaseLengthB">↓</button>
</div>
</section>
</div>
<script src="scripts/script.js"></script>
</body>
</html>
Another way to solve this is to use a thicker line-width and use isPointInStroke() instead.
var ctx = c.getContext("2d");
var path = new Path2D(); // to store and reuse path
var onLine = false; // state (for demo)
path.moveTo(10, 10); // store a line on path
path.lineTo(200, 100);
ctx.lineWidth = 16; // line width
render(); // initial render
function render() {
ctx.clearRect(0,0,300,150);
ctx.strokeStyle = onLine ? "#09f" : "#000"; // color based on state
ctx.stroke(path); // stroke path
}
c.onmousemove = function(e) { // demo: is mouse on stroke?
onLine = ctx.isPointInStroke(path, e.clientX, e.clientY);
render();
};
body, html {margin:0}
<canvas id=c></canvas>
Note: IE11 does not support the path argument - for it you will need to use ordinary path on the context itself (ctx.moveTo etc.)

How can I animate my background in a loop in node.js

Im making a multiplayer endless runner game and want to make the background move down in a loop with random obstacles in my way. So far I was able to make the scene with controls for the player, have set up a multiplayer aspect, and a sign in. However, I am not able to figure out how to set the background in a loop or add obstacles moving towards the player.
Heres the code:
App2.JS:
var mongojs = require("mongojs");
var db = mongojs('localhost:27017/myGame', ['account','progress']);
var express = require('express');
var app = express();
var serv = require('http').Server(app);
app.get('/',function(req, res) {
res.sendFile(__dirname + '/client/index2.html');
});
app.use('/client',express.static(__dirname + '/client'));
serv.listen(2000);
console.log("Server started.");
var SOCKET_LIST = {};
var Entity = function(){
var self = {
x:250,
y:250,
spdX:0,
spdY:0,
id:"",
}
self.update = function(){
self.updatePosition();
}
self.updatePosition = function(){
self.x += self.spdX;
self.y += self.spdY;
}
self.getDistance = function(pt){
return Math.sqrt(Math.pow(self.x-pt.x,2) + Math.pow(self.y-pt.y,2));
}
return self;
}
var Player = function(id){
var self = Entity();
self.id = id;
self.number = "" + Math.floor(10 * Math.random());
self.pressingRight = false;
self.pressingLeft = false;
self.pressingUp = false;
self.pressingDown = false;
self.pressingAttack = false;
self.mouseAngle = 0;
self.maxSpd = 25;
self.hp = 10;
self.hpMax = 10;
self.score = 0;
var super_update = self.update;
self.update = function(){
self.updateSpd();
super_update();
if(self.pressingAttack){
self.shootBullet(self.mouseAngle);
}
}
self.shootBullet = function(angle){
var b = Bullet(self.id,angle);
b.x = self.x;
b.y = self.y;
}
self.updateSpd = function(){
if(self.pressingRight && (self.x + 30) < 500)
self.spdX = self.maxSpd;
else if(self.pressingLeft && self.x > 0)
self.spdX = -self.maxSpd;
else
self.spdX = 0;
if(self.pressingUp)
self.spdY = 0;
else if(self.pressingDown)
self.spdY = 0;
else
self.spdY = 0;
}
self.getInitPack = function(){
return {
id:self.id,
x:self.x,
y:self.y,
number:self.number,
hp:self.hp,
hpMax:self.hpMax,
score:self.score,
};
}
self.getUpdatePack = function(){
return {
id:self.id,
x:self.x,
y:self.y,
hp:self.hp,
score:self.score,
}
}
Player.list[id] = self;
initPack.player.push(self.getInitPack());
return self;
}
Player.list = {};
Player.onConnect = function(socket){
var player = Player(socket.id);
socket.on('keyPress',function(data){
if(data.inputId === 'left')
player.pressingLeft = data.state;
else if(data.inputId === 'right')
player.pressingRight = data.state;
else if(data.inputId === 'up')
player.pressingUp = data.state;
else if(data.inputId === 'down')
player.pressingDown = data.state;
else if(data.inputId === 'attack')
player.pressingAttack = data.state;
else if(data.inputId === 'mouseAngle')
player.mouseAngle = data.state;
});
socket.emit('init',{
selfId:socket.id,
player:Player.getAllInitPack(),
bullet:Bullet.getAllInitPack(),
})
}
Player.getAllInitPack = function(){
var players = [];
for(var i in Player.list)
players.push(Player.list[i].getInitPack());
return players;
}
Player.onDisconnect = function(socket){
delete Player.list[socket.id];
removePack.player.push(socket.id);
}
Player.update = function(){
var pack = [];
for(var i in Player.list){
var player = Player.list[i];
player.update();
pack.push(player.getUpdatePack());
}
return pack;
}
var Bullet = function(parent,angle){
var self = Entity();
self.id = Math.random();
self.spdX = Math.cos(angle/180*Math.PI) * 10;
self.spdY = Math.sin(angle/180*Math.PI) * 10;
self.parent = parent;
self.timer = 0;
self.toRemove = false;
var super_update = self.update;
self.update = function(){
if(self.timer++ > 100)
self.toRemove = true;
super_update();
for(var i in Player.list){
var p = Player.list[i];
if(self.getDistance(p) < 32 && self.parent !== p.id){
p.hp -= 1;
if(p.hp <= 0){
var shooter = Player.list[self.parent];
if(shooter)
shooter.score += 1;
p.hp = p.hpMax;
p.x = Math.random() * 500;
p.y = Math.random() * 500;
}
self.toRemove = true;
}
}
}
self.getInitPack = function(){
return {
id:self.id,
x:self.x,
y:self.y,
};
}
self.getUpdatePack = function(){
return {
id:self.id,
x:self.x,
y:self.y,
};
}
Bullet.list[self.id] = self;
initPack.bullet.push(self.getInitPack());
return self;
}
Bullet.list = {};
Bullet.update = function(){
var pack = [];
for(var i in Bullet.list){
var bullet = Bullet.list[i];
bullet.update();
if(bullet.toRemove){
delete Bullet.list[i];
removePack.bullet.push(bullet.id);
} else
pack.push(bullet.getUpdatePack());
}
return pack;
}
Bullet.getAllInitPack = function(){
var bullets = [];
for(var i in Bullet.list)
bullets.push(Bullet.list[i].getInitPack());
return bullets;
}
var DEBUG = true;
var isValidPassword = function(data,cb){
db.account.find({username:data.username,password:data.password},function(err,res){
if(res.length > 0)
cb(true);
else
cb(false);
});
}
var isUsernameTaken = function(data,cb){
db.account.find({username:data.username},function(err,res){
if(res.length > 0)
cb(true);
else
cb(false);
});
}
var addUser = function(data,cb){
db.account.insert({username:data.username,password:data.password},function(err){
cb();
});
}
var io = require('socket.io')(serv,{});
io.sockets.on('connection', function(socket){
socket.id = Math.random();
SOCKET_LIST[socket.id] = socket;
socket.on('signIn',function(data){
isValidPassword(data,function(res){
if(res){
Player.onConnect(socket);
socket.emit('signInResponse',{success:true});
} else {
socket.emit('signInResponse',{success:false});
}
});
});
socket.on('signUp',function(data){
isUsernameTaken(data,function(res){
if(res){
socket.emit('signUpResponse',{success:false});
} else {
addUser(data,function(){
socket.emit('signUpResponse',{success:true});
});
}
});
});
socket.on('disconnect',function(){
delete SOCKET_LIST[socket.id];
Player.onDisconnect(socket);
});
socket.on('sendMsgToServer',function(data){
var playerName = ("" + socket.id).slice(2,7);
for(var i in SOCKET_LIST){
SOCKET_LIST[i].emit('addToChat',playerName + ': ' + data);
}
});
socket.on('evalServer',function(data){
if(!DEBUG)
return;
var res = eval(data);
socket.emit('evalAnswer',res);
});
});
var initPack = {player:[],bullet:[]};
var removePack = {player:[],bullet:[]};
setInterval(function(){
var pack = {
player:Player.update(),
bullet:Bullet.update(),
}
for(var i in SOCKET_LIST){
var socket = SOCKET_LIST[i];
socket.emit('init',initPack);
socket.emit('update',pack);
socket.emit('remove',removePack);
}
initPack.player = [];
initPack.bullet = [];
removePack.player = [];
removePack.bullet = [];
},1000/25);
indexCars2.html:
<div id="signDiv">
Username: <input id="signDiv-username" type="text"></input><br>
Password: <input id="signDiv-password" type="password"></input>
<button id="signDiv-signIn">Sign In</button>
<button id="signDiv-signUp">Sign Up</button>
</div>
<div id="animate"
style = "position: relative;"
style = "border: 1px solid green;"
style = "background: yellow; "
style = "width: 100;"
style = "height: 100;"
style = "z-index: 5;">
Sample
</div>
<div id="gameDiv" style="display:none;">
<canvas id="ctx" width="500" height="500" style="border:1px solid #000000;"></canvas>
<div id="chat-text" style="width:500px;height:100px;overflow-y:scroll">
<div>Hello!</div>
</div>
<form id="chat-form">
<input id="chat-input" type="text" style="width:500px"></input>
</form>
</div>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script>
$(document).ready(function(e) {
var width = "+=" + $(document).width();
$("#animate").animate({
left: width
}, 5000, function() {
// Animation complete.
});
});</script>
<script>
// var WIDTH = 500;
// var HEIGHT = 500;
var socket = io();
//sign
var signDiv = document.getElementById('signDiv');
var signDivUsername = document.getElementById('signDiv-username');
var signDivSignIn = document.getElementById('signDiv-signIn');
var signDivSignUp = document.getElementById('signDiv-signUp');
var signDivPassword = document.getElementById('signDiv-password');
signDivSignIn.onclick = function(){
socket.emit('signIn',{username:signDivUsername.value,password:signDivPassword.value});
}
signDivSignUp.onclick = function(){
socket.emit('signUp',{username:signDivUsername.value,password:signDivPassword.value});
}
socket.on('signInResponse',function(data){
if(data.success){
signDiv.style.display = 'none';
gameDiv.style.display = 'inline-block';
} else
alert("Sign in unsuccessul.");
});
socket.on('signUpResponse',function(data){
if(data.success){
alert("Sign up successul.");
} else
alert("Sign up unsuccessul.");
});
//chat
var chatText = document.getElementById('chat-text');
var chatInput = document.getElementById('chat-input');
var chatForm = document.getElementById('chat-form');
socket.on('addToChat',function(data){
chatText.innerHTML += '<div>' + data + '</div>';
});
socket.on('evalAnswer',function(data){
console.log(data);
});
chatForm.onsubmit = function(e){
e.preventDefault();
if(chatInput.value[0] === '/')
socket.emit('evalServer',chatInput.value.slice(1));
else
socket.emit('sendMsgToServer',chatInput.value);
chatInput.value = '';
}
//game
var Img = {};
Img.player = new Image();
Img.player.src = '/client/img/lamboS.png';
Img.bullet = new Image();
Img.bullet.src = '/client/img/bullet.png';
Img.map = new Image();
Img.map.src = '/client/img/road.png';
var ctx = document.getElementById("ctx").getContext("2d");
ctx.font = '30px Arial';
var Player = function(initPack){
var self = {};
self.id = initPack.id;
self.number = initPack.number;
self.x = initPack.x;
self.y = initPack.y;
self.hp = initPack.hp;
self.hpMax = initPack.hpMax;
self.score = initPack.score;
self.draw = function(){
// var x = self.x - Player.list[selfId].x + WIDTH/2;
// var y = self.y - Player.list[selfId].y + HEIGHT/2;
var hpWidth = 30 * self.hp / self.hpMax;
ctx.fillStyle = 'red';
ctx.fillRect(self.x - hpWidth/2,self.y - 40,hpWidth,4);
var width = Img.player.width;
var height = Img.player.height;
ctx.drawImage(Img.player,
0,0,Img.player.width,Img.player.height,
self.x-width/2,self.y-height/2,width,height);
//ctx.fillText(self.score,self.x,self.y-60);
}
Player.list[self.id] = self;
return self;
}
Player.list = {};
var Bullet = function(initPack){
var self = {};
self.id = initPack.id;
self.x = initPack.x;
self.y = initPack.y;
self.draw = function(){
var width = Img.bullet.width/2;
var height = Img.bullet.height/2;
// var x = self.x - Player.list[selfId].x + WIDTH/2;
// var y = self.y - Player.list[selfId].y + HEIGHT/2;
ctx.drawImage(Img.bullet,
0,0,Img.bullet.width,Img.bullet.height,
self.x-width/2,self.y-height/2,width,height);
}
Bullet.list[self.id] = self;
return self;
}
Bullet.list = {};
var selfId = null;
socket.on('init',function(data){
if(data.selfId)
selfId = data.selfId;
//{ player : [{id:123,number:'1',x:0,y:0},{id:1,number:'2',x:0,y:0}], bullet: []}
for(var i = 0 ; i < data.player.length; i++){
new Player(data.player[i]);
}
for(var i = 0 ; i < data.bullet.length; i++){
new Bullet(data.bullet[i]);
}
});
socket.on('update',function(data){
//{ player : [{id:123,x:0,y:0},{id:1,x:0,y:0}], bullet: []}
for(var i = 0 ; i < data.player.length; i++){
var pack = data.player[i];
var p = Player.list[pack.id];
if(p){
if(pack.x !== undefined)
p.x = pack.x;
if(pack.y !== undefined)
p.y = pack.y;
if(pack.hp !== undefined)
p.hp = pack.hp;
if(pack.score !== undefined)
p.score = pack.score;
}
}
for(var i = 0 ; i < data.bullet.length; i++){
var pack = data.bullet[i];
var b = Bullet.list[data.bullet[i].id];
if(b){
if(pack.x !== undefined)
b.x = pack.x;
if(pack.y !== undefined)
b.y = pack.y;
}
}
for(var i = 0 ; i < data.bullet.length; i++){
var pack = data.bullet[i];
var b = Bullet.list[data.bullet[i].id];
if(b){
if(pack.x !== undefined)
b.x = pack.x;
if(pack.y !== undefined)
b.y = pack.y;
}
}
});
socket.on('remove',function(data){
//{player:[12323],bullet:[12323,123123]}
for(var i = 0 ; i < data.player.length; i++){
delete Player.list[data.player[i]];
}
for(var i = 0 ; i < data.bullet.length; i++){
delete Bullet.list[data.bullet[i]];
}
});
setInterval(function(){
if(!selfId)
return;
ctx.clearRect(0,0,500,500);
drawMap();
drawScore();
for(var i in Player.list)
Player.list[i].draw();
for(var i in Bullet.list)
Bullet.list[i].draw();
},40);
var drawMap = function(){
var x = 0;
var y = 0;
// var x = WIDTH/2 - Player.list[selfId].x;
// var y = HEIGHT/2 - Player.list[selfId].y;
ctx.drawImage(Img.map, x, y);
// for(x = 0; x < 5; x += 100){
//// ctx.drawImage(Img.map, x, y);
// }
}
var drawScore = function(){
ctx.fillStyle = 'red';
ctx.fillText(Player.list[selfId].score,10,30);
}
document.onkeydown = function(event){
if(event.keyCode === 68) //d
socket.emit('keyPress',{inputId:'right',state:true});
else if(event.keyCode === 83) //s
socket.emit('keyPress',{inputId:'down',state:true});
else if(event.keyCode === 65) //a
socket.emit('keyPress',{inputId:'left',state:true});
else if(event.keyCode === 87) // w
socket.emit('keyPress',{inputId:'up',state:true});
}
document.onkeyup = function(event){
if(event.keyCode === 68) //d
socket.emit('keyPress',{inputId:'right',state:false});
else if(event.keyCode === 83) //s
socket.emit('keyPress',{inputId:'down',state:false});
else if(event.keyCode === 65) //a
socket.emit('keyPress',{inputId:'left',state:false});
else if(event.keyCode === 87) // w
socket.emit('keyPress',{inputId:'up',state:false});
}
document.onmousedown = function(event){
socket.emit('keyPress',{inputId:'attack',state:true});
}
document.onmouseup = function(event){
socket.emit('keyPress',{inputId:'attack',state:false});
}
document.onmousemove = function(event){
var x = -250 + event.clientX - 8;
var y = -250 + event.clientY - 8;
var angle = Math.atan2(y,x) / Math.PI * 180;
socket.emit('keyPress',{inputId:'mouseAngle',state:angle});
}
</script>
The idea in endless runners is to actually move the objects towards the player at constant speed(i.e. speed of the player). As soon as they get off the screen you can stop updating them. Check out this http://blog.sklambert.com/html5-game-tutorial-module-pattern/?utm_content=buffer18ac6&utm_medium=social&utm_source=twitter.com&utm_campaign=buffer

Jquery stopped working

I'm developping this mobile app and I'm usint this (https://github.com/krisrak/appframework-templates/blob/master/template-CarouselViewApp.html) as a carousel to change through content on a page. http://jsfiddle.net/nafis56/qCkqb/
So for this I need to mess around in HTML, CSS and Jquery. Unfortonetly I'm still very green at javascript so I need your help. I changed an ID to a Class because I need to call it more than once in the same page. In the original template I refeered to, it comes as an ID. So I did this to change it:
Changed matching code on html to call it as a Class.
<div class="panel" title="Desiree Charms" id="desiree_charms" style="overflow: hidden;"
data-appbuilder-object="page">
<div class="carousel">
<div class="carousel_page">
<h2>Desiree Charms</h2>
<p><img src="images/desiree_charms.jpg" style="width: 85%; height: 85%; display: block; margin-left: auto; margin-right: auto "
data-appbuilder-object="image" class="" title="">
</p>
</div>
<div class="carousel_page">
<h2>Page Two</h2>
<p>Text and images for Page Two goes here. Swipe to go to the
next page.</p>
</div>
</div>
<div class="carousel_dots"></div>
</div>
also this on the html.
<script>
$.ui.autoLaunch = false;
$.ui.animateHeaders = false;
$(document).ready(function(){
$.ui.launch();
});
$.ui.ready(function(){
carouselSetup();
});
function carouselSetup(){
// set size of carousel
$(".carousel").width($(".carousel").closest(".panel").width());
$(".carousel").height($(".carousel").closest(".panel").height()-25);
var options={
vertical:false, // page up/down
horizontal:true, // page left/right
pagingDiv:"carousel_dots", // div to hold the dots for paging
pagingCssName:"carousel_paging", //classname for the paging dots
pagingCssNameSelected: "carousel_paging_selected", //classname for the selected page dots
wrap:true //Creates a continuous carousel
}
var carousel = $(".carousel").carousel(options);
}
Changed # to . on Css.
.carousel {
overflow:hidden;
margin:0 -10px;
}
.carousel_page {
overflow: auto;
-webkit-scrolling:touch;
padding:0 10px;
}
.carousel_dots {
text-align: center;
margin-left: auto;
margin-right: auto;
clear: both;
position:relative;
top:0;
z-index:200;
}
.carousel_paging {
border-radius: 10px;
background: #ccc;
width: 10px;
height: 10px;
display:inline-block;
}
.carousel_paging_selected {
border-radius: 10px;
background: #000;
width: 10px;
height: 10px;
display:inline-block;
}
.carousel h2 {
text-align: center;
}
This is the jquery ( I didn't change anything)
/**
* af.web.carousel - a carousel library for App Framework apps
* #copyright 2011 - Intel
*
*/
(function($) {
var cache = [];
var objId=function(obj){
if(!obj.afmCarouselId) obj.afmCarouselId=$.uuid();
return obj.afmCarouselId;
}
$.fn.carousel = function(opts) {
var tmp, id;
for (var i = 0; i < this.length; i++) {
//cache system
id = objId(this[i]);
if(!cache[id]){
tmp = new carousel(this[i], opts);
cache[id] = tmp;
} else {
tmp = cache[id];
}
}
return this.length == 1 ? tmp : this;
};
var carousel = (function() {
var translateOpen =$.feat.cssTransformStart;
var translateClose = $.feat.cssTransformEnd;
var carousel = function(containerEl, opts) {
if (typeof containerEl === "string" || containerEl instanceof String) {
this.container = document.getElementById(containerEl);
} else {
this.container = containerEl;
}
if (!this.container) {
alert("Error finding container for carousel " + containerEl);
return;
}
if (this instanceof carousel) {
for (var j in opts) {
if (opts.hasOwnProperty(j)) {
this[j] = opts[j];
}
}
} else {
return new carousel(containerEl, opts);
}
var that = this;
af(this.container).bind('destroy', function(e){
var id = that.container.afmCarouselId;
//window event need to be cleaned up manually, remaining binds are automatically killed in the dom cleanup process
window.removeEventListener("orientationchange", that.orientationHandler, false);
if(cache[id]) delete cache[id];
e.stopPropagation();
});
this.pagingDiv = this.pagingDiv ? document.getElementById(this.pagingDiv) : null;
// initial setup
this.container.style.overflow = "hidden";
if (this.vertical) {
this.horizontal = false;
}
var el = document.createElement("div");
this.container.appendChild(el);
var $el=$(el);
var $container=$(this.container);
var data = Array.prototype.slice.call(this.container.childNodes);
while(data.length>0)
{
var myEl=data.splice(0,1);
myEl=$container.find(myEl);
if(myEl.get(0)==el)
continue;
$el.append(myEl.get(0));
}
if (this.horizontal) {
el.style.display = "block";
el.style['float']="left";
}
else {
el.style.display = "block";
}
this.el = el;
this.refreshItems();
var afEl = af(el);
afEl.bind('touchmove', function(e) {that.touchMove(e);});
afEl.bind('touchend', function(e) {that.touchEnd(e);});
afEl.bind('touchstart', function(e) {that.touchStart(e);});
this.orientationHandler = function() {that.onMoveIndex(that.carouselIndex,0);};
window.addEventListener("orientationchange", this.orientationHandler, false);
};
carousel.prototype = {
wrap:true,
startX: 0,
startY: 0,
dx: 0,
dy: 0,
glue: false,
myDivWidth: 0,
myDivHeight: 0,
cssMoveStart: 0,
childrenCount: 0,
carouselIndex: 0,
vertical: false,
horizontal: true,
el: null,
movingElement: false,
container: null,
pagingDiv: null,
pagingCssName: "carousel_paging",
pagingCssNameSelected: "carousel_paging_selected",
pagingFunction: null,
lockMove:false,
okToMove: false,
// handle the moving function
touchStart: function(e) {
this.okToMove = false;
this.myDivWidth = numOnly(this.container.clientWidth);
this.myDivHeight = numOnly(this.container.clientHeight);
this.lockMove=false;
if (e.touches[0].target && e.touches[0].target.type !== undefined) {
var tagname = e.touches[0].target.tagName.toLowerCase();
if (tagname === "select" || tagname === "input" || tagname === "button") // stuff we need to allow
{
return;
}
}
if (e.touches.length === 1) {
this.movingElement = true;
this.startY = e.touches[0].pageY;
this.startX = e.touches[0].pageX;
var cssMatrix=$.getCssMatrix(this.el);
if (this.vertical) {
try {
this.cssMoveStart = numOnly(cssMatrix.f);
} catch (ex1) {
this.cssMoveStart = 0;
}
} else {
try {
this.cssMoveStart = numOnly(cssMatrix.e);
} catch (ex1) {
this.cssMoveStart = 0;
}
}
}
},
touchMove: function(e) {
if(!this.movingElement)
return;
if (e.touches.length > 1) {
return this.touchEnd(e);
}
var rawDelta = {
x: e.touches[0].pageX - this.startX,
y: e.touches[0].pageY - this.startY
};
if (this.vertical) {
var movePos = { x: 0, y: 0 };
this.dy = e.touches[0].pageY - this.startY;
this.dy += this.cssMoveStart;
movePos.y = this.dy;
e.preventDefault();
//e.stopPropagation();
} else {
if ((!this.lockMove&&isHorizontalSwipe(rawDelta.x, rawDelta.y))||Math.abs(this.dx)>5) {
var movePos = {x: 0,y: 0};
this.dx = e.touches[0].pageX - this.startX;
this.dx += this.cssMoveStart;
e.preventDefault();
// e.stopPropagation();
movePos.x = this.dx;
}
else
return this.lockMove=true;
}
var totalMoved = this.vertical ? ((this.dy % this.myDivHeight) / this.myDivHeight * 100) * -1 : ((this.dx % this.myDivWidth) / this.myDivWidth * 100) * -1; // get a percentage of movement.
if (!this.okToMove) {
oldStateOkToMove= this.okToMove;
this.okToMove = this.glue ? Math.abs(totalMoved) > this.glue && Math.abs(totalMoved) < (100 - this.glue) : true;
if (this.okToMove && !oldStateOkToMove) {
$.trigger(this,"movestart",[this.el]);
}
}
if (this.okToMove && movePos)
this.moveCSS3(this.el, movePos);
},
touchEnd: function(e) {
if (!this.movingElement) {
return;
}
$.trigger(this,"movestop",[this.el]);
// e.preventDefault();
// e.stopPropagation();
var runFinal = false;
// try {
var cssMatrix=$.getCssMatrix(this.el);
var endPos = this.vertical ? numOnly(cssMatrix.f) : numOnly(cssMatrix.e);
if (1==2&&endPos > 0) {
this.moveCSS3(this.el, {
x: 0,
y: 0
}, "300");
} else {
var totalMoved = this.vertical ? ((this.dy % this.myDivHeight) / this.myDivHeight * 100) * -1 : ((this.dx % this.myDivWidth) / this.myDivWidth * 100) * -1; // get a percentage of movement.
// Only need
// to drag 3% to trigger an event
var currInd = this.carouselIndex;
if (endPos < this.cssMoveStart && totalMoved > 3) {
currInd++; // move right/down
} else if ((endPos > this.cssMoveStart && totalMoved < 97)) {
currInd--; // move left/up
}
var toMove=currInd;
//Checks for infinite - moves to placeholders
if(this.wrap){
if (currInd > (this.childrenCount - 1)) {
currInd = 0;
toMove=this.childrenCount;
}
if (currInd < 0) {
currInd = this.childrenCount-1;
toMove=-1;
}
}
else {
if(currInd<0)
currInd=0;
if(currInd>this.childrenCount-1)
currInd=this.childrenCount-1;
toMove=currInd;
}
var movePos = {
x: 0,
y: 0
};
if (this.vertical) {
movePos.y = (toMove * this.myDivHeight * -1);
}
else {
movePos.x = (toMove * this.myDivWidth * -1);
}
this.moveCSS3(this.el, movePos, "150");
if (this.pagingDiv && this.carouselIndex !== currInd) {
document.getElementById(this.container.id + "_" + this.carouselIndex).className = this.pagingCssName;
document.getElementById(this.container.id + "_" + currInd).className = this.pagingCssNameSelected;
}
if (this.carouselIndex != currInd)
runFinal = true;
this.carouselIndex = currInd;
//This is for the infinite ends - will move to the correct position after animation
if(this.wrap){
if(toMove!=currInd){
var that=this;
window.setTimeout(function(){
that.onMoveIndex(currInd,"1ms");
},155);
}
}
}
//} catch (e) {
// console.log(e);
// }
this.dx = 0;
this.movingElement = false;
this.startX = 0;
this.dy = 0;
this.startY = 0;
if (runFinal && this.pagingFunction && typeof this.pagingFunction == "function")
this.pagingFunction(this.carouselIndex);
},
onMoveIndex: function(newInd,transitionTime) {
this.myDivWidth = numOnly(this.container.clientWidth);
this.myDivHeight = numOnly(this.container.clientHeight);
var runFinal = false;
if(document.getElementById(this.container.id + "_" + this.carouselIndex))
document.getElementById(this.container.id + "_" + this.carouselIndex).className = this.pagingCssName;
var newTime = Math.abs(newInd - this.carouselIndex);
var ind = newInd;
if (ind < 0)
ind = 0;
if (ind > this.childrenCount - 1) {
ind = this.childrenCount - 1;
}
var movePos = {
x: 0,
y: 0
};
if (this.vertical) {
movePos.y = (ind * this.myDivHeight * -1);
}
else {
movePos.x = (ind * this.myDivWidth * -1);
}
var time =transitionTime?transitionTime: 50 + parseInt((newTime * 20));
this.moveCSS3(this.el, movePos, time);
if (this.carouselIndex != ind)
runFinal = true;
this.carouselIndex = ind;
if (this.pagingDiv) {
var tmpEl = document.getElementById(this.container.id + "_" + this.carouselIndex);
if(tmpEl) tmpEl.className = this.pagingCssNameSelected;
}
if (runFinal && this.pagingFunction && typeof this.pagingFunction == "function")
this.pagingFunction(currInd);
},
moveCSS3: function(el, distanceToMove, time, timingFunction) {
if (!time)
time = 0;
else
time = parseInt(time);
if (!timingFunction)
timingFunction = "linear";
el.style[$.feat.cssPrefix+"Transform"] = "translate" + translateOpen + distanceToMove.x + "px," + distanceToMove.y + "px" + translateClose;
el.style[$.feat.cssPrefix+"TransitionDuration"] = time + "ms";
el.style[$.feat.cssPrefix+"BackfaceVisibility"] = "hidden";
el.style[$.feat.cssPrefix+"TransitionTimingFunction"] = timingFunction;
},
addItem: function(el) {
if (el && el.nodeType) {
this.container.childNodes[0].appendChild(el);
this.refreshItems();
}
},
refreshItems: function() {
var childrenCounter = 0;
var that = this;
var el = this.el;
$(el).children().find(".prevBuffer").remove();
$(el).children().find(".nextBuffer").remove();
n = el.childNodes[0];
var widthParam;
var heightParam = "100%";
var elems = [];
for (; n; n = n.nextSibling) {
if (n.nodeType === 1) {
elems.push(n);
childrenCounter++;
}
}
//Let's put the buffers at the start/end
if(this.wrap){
var prep=$(elems[elems.length-1]).clone().get(0);
$(el).prepend(prep);
var tmp=$(elems[0]).clone().get(0);
$(el).append(tmp);
elems.push(tmp);
elems.unshift(prep);
tmp.style.position="absolute";
prep.style.position="absolute";
}
var param = (100 / childrenCounter) + "%";
this.childrenCount = childrenCounter;
widthParam = parseFloat(100 / childrenCounter) + "%";
for (var i = 0; i < elems.length; i++) {
if (this.horizontal) {
elems[i].style.width = widthParam;
elems[i].style.height = "100%";
elems[i].style['float']="left";
}
else {
elems[i].style.height = widthParam;
elems[i].style.width = "100%";
elems[i].style.display = "block";
}
}
//Clone the first and put it at the end
this.moveCSS3(el, {
x: 0,
y: 0
});
if (this.horizontal) {
el.style.width = Math.ceil((this.childrenCount) * 100) + "%";
el.style.height = "100%";
el.style['min-height'] = "100%"
if(this.wrap){
prep.style.left="-"+widthParam;
tmp.style.left="100%";
}
}
else {
el.style.width = "100%";
el.style.height = Math.ceil((this.childrenCount) * 100) + "%";
el.style['min-height'] = Math.ceil((this.childrenCount) * 100) + "%";
if(this.wrap){
prep.style.top="-"+widthParam;
tmp.style.top="100%";
}
}
// Create the paging dots
if (this.pagingDiv) {
this.pagingDiv.innerHTML = ""
for (i = 0; i < this.childrenCount; i++) {
var pagingEl = document.createElement("div");
pagingEl.id = this.container.id + "_" + i;
pagingEl.pageId = i;
if (i !== this.carouselIndex) {
pagingEl.className = this.pagingCssName;
}
else {
pagingEl.className = this.pagingCssNameSelected;
}
pagingEl.onclick = function() {
that.onMoveIndex(this.pageId);
};
var spacerEl = document.createElement("div");
spacerEl.style.width = "20px";
if(this.horizontal){
spacerEl.style.display = "inline-block";
spacerEl.innerHTML = " ";
}
else{
spacerEl.innerHTML=" ";
spacerEl.style.display="block";
}
this.pagingDiv.appendChild(pagingEl);
if (i + 1 < (this.childrenCount))
this.pagingDiv.appendChild(spacerEl);
pagingEl = null;
spacerEl = null;
}
if(this.horizontal){
this.pagingDiv.style.width = (this.childrenCount) * 50 + "px";
this.pagingDiv.style.height = "25px";
}
else {
this.pagingDiv.style.height = (this.childrenCount) * 50 + "px";
this.pagingDiv.style.width = "25px";
}
}
this.onMoveIndex(this.carouselIndex);
}
};
return carousel;
})();
function isHorizontalSwipe(xAxis, yAxis) {
var X = xAxis;
var Y = yAxis;
var Z = Math.round(Math.sqrt(Math.pow(X,2)+Math.pow(Y,2))); //the distance - rounded - in pixels
var r = Math.atan2(Y,X); //angle in radians
var swipeAngle = Math.round(r*180/Math.PI); //angle in degrees
if ( swipeAngle < 0 ) { swipeAngle = 360 - Math.abs(swipeAngle); } // for negative degree values
if (((swipeAngle <= 215) && (swipeAngle >= 155)) || ((swipeAngle <= 45) && (swipeAngle >= 0)) || ((swipeAngle <= 360) && (swipeAngle >= 315))) // horizontal angles with threshold
{return true; }
else {return false}
}
})(af);
Now, on the CSS file when I change .carousel_dots to #carousel_dots as it was originally. The carousel starts working. The problem is I need it as a class not an ID.
I'm pretty sure the problem is in the jquery, somewhere in there I need to set carousel_dots as a class and not an ID, but where?
Any help will be much apreciated, thanks.
jQuery is designed to trigger on HTML selectors, either elements, ID's or Class's. It's very common for it to trigger on ID's because, as you identified, they occur once and that isolates the action to that particular item.
I know that you changed the ID's to Class's because you want to use the CSS class multiple times. You can do this by using Class's. But, to maintain the jQuery logic, you should not change the ID's to Class's for that purpose. Use the ID's to synch with jQuery. Use Class's to control your CSS.
It's difficult to advise you regarding the case you displayed because you didn't identify the initial status and exactly how you changed it. If you can do that, we can be specific about what changes you should make. Good luck.

How do I create an animated tile in pixi.js with good performance?

How can I use PIXI js to animate from spritesheets using TiledSprites? I need to animate a tiled sprite background from a sprite sheet.
Currently there is API calls to animate a tiled sprite in the PIXI.js API. I have created the following class to help me load and animate tiled backgrounds.
/////////////////////////////////////////////////////////////////////////////
/// Tiling Sprite Animation
/////////////////////////////////////////////////////////////////////////////
(function() {
PIXI.TilingSpriteAnimation = function(texture, frames, rows, frametime, loop) {
PIXI.TilingSprite.call(
this, texture,
VIEWPORTWIDTH,
this._texture.baseTexture.height);
this._stop = true;
this._texture = new PIXI.Texture(texture);
this.frameTime = frametime;
this.loop = loop || true;
this.curX = 0;
this.curY = 0;
this.fh = this._texture.height / rows;
this.fw = this._texture.width / frames;
this.ticks = 0;
this.maxFrames = frames;
this.maxRows = rows;
this.done = false;
this.calculateFrame();
};
PIXI.TilingSpriteAnimation.prototype = Object.create( PIXI.TilingSprite.prototype );
PIXI.TilingSpriteAnimation.prototype.constructor = PIXI.TilingSpriteAnimation;
Object.defineProperty(PIXI.TilingSpriteAnimation.prototype, 'texture', {
get: function() {
return this._texture;
}
});
PIXI.TilingSpriteAnimation.prototype.update = function() {
console.log(this.ticks);
if(!this._stop) {
this.ticks += 1;
}
if (this.done == false) {
if (this.ticks >= this.frameTime) {
this.curX++;
this.ticks = 0;
if (this.curX == this.maxFrames) {
this.curX = 0;
this.curY++;
if (this.curY == this.maxRows) {
this.curY = 0;
if (!this.loop)
this.done = true;
}
}
this.calculateFrame();
}
}
};
PIXI.TilingSpriteAnimation.prototype.goto = function(frame, row) {
this.curX = frame;
this.curY = row || 0;
};
PIXI.TilingSpriteAnimation.prototype.stop = function() {
this._stop = true;
};
PIXI.TilingSpriteAnimation.prototype.play = function() {
this._stop = false;
};
PIXI.TilingSpriteAnimation.prototype.calculateFrame = function() {
this.texture.frame.x = this.curX * this.fw;
this.texture.frame.y = this.curY * this.fh;
this.texture.frame.width = this.fw;
this.texture.frame.height = this.fh;
this.texture.setFrame(this.texture.frame);
this.generateTilingTexture(this.texture);
};
}).call(this);
This code is however highly inefficient because it calculates a new TiledTexture each time a new frame is entered. How can I optimize this?
I struggeled some time with this but came up with the following. I hope it helps
/////////////////////////////////////////////////////////////////////////////
/// Tiling Sprite Animation
/////////////////////////////////////////////////////////////////////////////
(function() {
PIXI.TilingSpriteAnimation = function(texture, frames, frametime, loop) {
PIXI.TilingSprite.call(
this, texture,
VIEWPORTWIDTH,
VIEWPORTHEIGHT);
this._stop = true;
this._texture = new PIXI.Texture(texture);
this.frameTime = frametime;
this.loop = loop || true;
this.curX = 0;
this.fh = this._texture.height;
this.fw = this._texture.width / frames;
this.ticks = 0;
this.maxFrames = frames;
for (var i=0;i<frames;i++){
this.preLoadFrame(i);
}
this.calculateFrame();
};
PIXI.TilingSpriteAnimation.prototype = Object.create( PIXI.TilingSprite.prototype );
PIXI.TilingSpriteAnimation.prototype.constructor = PIXI.TilingSpriteAnimation;
Object.defineProperty(PIXI.TilingSpriteAnimation.prototype, 'texture', {
get: function() {
return this._texture;
}
});
PIXI.TilingSpriteAnimation.prototype.update = function() {
if (this._stop == false) {
this.ticks += 1;
if (this.ticks >= this.frameTime) {
this.curX++;
this.ticks = 0;
if (this.curX == this.maxFrames) {
this.curX = 0;
if (!this.loop) {
this._stop = true;
}
}
this.calculateFrame();
}
}
};
PIXI.TilingSpriteAnimation.prototype.goto = function(frame) {
this.curX = frame;
};
PIXI.TilingSpriteAnimation.prototype.stop = function() {
this._stop = true;
};
PIXI.TilingSpriteAnimation.prototype.play = function() {
this._stop = false;
};
PIXI.TilingSpriteAnimation.prototype.calculateFrame = function() {
this.tilingTexture = PIXI.Texture.fromFrame("texture" + this.curX);
};
PIXI.TilingSpriteAnimation.prototype.preLoadFrame = function(frame) {
var text = new PIXI.TilingSprite(this.texture);
text.texture.frame.x = frame * this.fw;
text.texture.frame.y = 0;
text.texture.frame.width = this.fw;
text.texture.frame.height = this.fh;
text.texture.setFrame(text.texture.frame);
text.generateTilingTexture(text);
PIXI.Texture.addTextureToCache(text.tilingTexture, "texture" + frame)
};
}).call(this);

Converting jquery to javascript progress bar

Please help me convert this JQuery to Javascript progress bar script
var generateButton = document.getElementById("generate");
if (generateButton.addEventListener) {
generateButton.addEventListener("click", random, false);
}
else if (generateButton.attachEvent) {
generateButton.attachEvent('onclick', random);
}
function random(e) {
setTimeout(function(){
$('.progress .bar').each(function() {
var me = $(this);
var perc = me.attr("data-percentage");
//TODO: left and right text handling
var current_perc = 0;
var progress = setInterval(function() {
if (current_perc>=perc) {
clearInterval(progress);
} else {
current_perc +=1;
me.css('width', (current_perc)+'%');
}
me.text((current_perc)+'%');
}, 50);
});
},300);
var num = Math.random();
var greetingString = num;
document.getElementById("rslt").innerText = greetingString;
}
Here is the Live version: http://jsfiddle.net/chjjK/9/
Pretty easy actually, use document.getElementsByClassName and a for loop to replace the each:
var bar = document.getElementsByClassName("bar");
for (var i = 0; i < bar.length; i++) {
var me = bar[i];
var perc = me.getAttribute("data-percentage");
var current_perc = 0;
var progress = setInterval(function() {
if (current_perc>=perc) {
clearInterval(progress);
} else {
current_perc +=1;
me.style.width = current_perc+'%';
}
me.innerHTML = ((current_perc)+'%');
}, 50);
}
}, 300);
Demo: http://jsfiddle.net/chjjK/13/

Categories

Resources