Animation Array in JavaScript - javascript

I've come up with this little animation that uses images in an array, but it's sloppy. What I'd really like is to modularize it so that I can use multiple instances of the same function to animate different arrays depending on which key is pressed. Also, I'd like to get it so that the animation stops when the key is released, if possible. I realize that calling all of those variables globally is a big no-no, but I have no idea how to make it work otherwise! Last but not least, I'd like to figure out how to get that last bit of inline script over to the external file and have it still work correctly. Any help would be much appreciated! But please note, I'm a novice with JavaScript, so please try to be as specific/detailed as possible so I can learn from your wisdom! Thank you!
I've created a jsfiddle.
HTML:
<div id="wrapper">
<span id="jajo"><img id="my_img" src="jajo.png" /></span>
<script>element = document.getElementById("jajo"); </script>
</div><!--wrapper-->
JavaScript:
var i = 0;
var element;
var waveArray = ["wave0.png","wave1.png","wave2.png","wave3.png","wave4.png","wave5.png"];
var jumpArray = ["jump0.png","jump1.png","jump2.png","jump3.png","jump4.png","jump5.png"];
var foodArray = ["food0.png","food1.png","food2.png","food3.png","food4.png","food5.png"];
document.onkeydown = function(event) {
var keyPress = String.fromCharCode(event.keyCode);
if(keyPress == "W") { // if "w" is pressed, display wave animation
increment ();
document.onkeyup = function(event) { // if "w" is released, display default image
document.getElementById("jajo").innerHTML= "<img alt='Jajo' src='jajo.png'>";
}
} else if(keyPress == "A") { // if "a" is pressed, display jump animation
} else if(keyPress == "S") { // if "s" is pressed, display food animation
}
}
function increment (){
i++;
if(i > (waveArray.length - 1)){
i = 0;
}
setTimeout(animation,1000/30);
}
function animation() {
var img = '<img src="' + waveArray[i] + '" alt="Jajo" />';
element.innerHTML = img;
setTimeout(increment, 2000/30);
}

Demo
http://jsfiddle.net/ghQwF/4/
Module
var animation = (function() {
var delay = 1000 / 30;
var map = {}, active = [], timer;
function animate() {
for(var i=0, l=active.length; i<l; ++i) {
var data = map[active[i]];
++data.index;
data.index %= data.array.length;
data.image.src = data.array[data.index];
}
timer = setTimeout(animate, delay);
}
function begin(e) {
var key = String.fromCharCode(e.keyCode),
data = map[key];
if(!data) return;
if(!active.length) timer = setTimeout(animate, delay);
if(!~active.indexOf(key)) active.push(key);
}
function end(e) {
var key = String.fromCharCode(e.keyCode),
data = map[key];
if(!data) return;
data.image.src = data.default;
var index = active.indexOf(key);
if(!~index) return;
active.splice(index, 1);
if(!active.length) clearTimeout(timer);
}
return {
add: function(data) {
data.index = data.index || 0;
data.image = data.image || data.target.getElementsByTagName('img')[0];
data.default = data.default || data.image.src;
map[data.key] = data;
},
remove: function(key) {
delete map[key];
},
enable: function() {
document.addEventListener('keydown', begin, false);
document.addEventListener('keyup', end, false);
},
disable: function() {
document.removeEventListener('keydown', begin, false);
document.removeEventListener('keyup', end, false);
clearTimeout(timer);
active = [];
}
};
})();
Example
animation.enable();
animation.add({
key: 'W',
target: document.getElementById('jajo'),
array: [
"http://static.spoonful.com/sites/default/files/styles/square_128x128/public/crafts/fingerprint-flowers-spring-craft-photo-420x420-aformaro-01.jpg",
"http://static.spoonful.com/sites/default/files/styles/square_128x128/public/crafts/paper-flowers-spring-craft-photo-420x420-aformaro-11.jpg",
"http://static.spoonful.com/sites/default/files/styles/square_128x128/public/crafts/tissue-paper-flowers-kaboose-craft-photo-350-fs-IMG_8971_rdax_65.jpg"
]
});
animation.add({ /* ... */ });
Methods
add
Adds a new animation, with parameters:
key: key to activate animation
target: wrapper of the image (optional if image is specified)
image: image to animate (optional, defaults to first image in target)
default: default url of the image (optional, defaults to original url)
index: initial position in array (optional, defaults to 0)
array: array of images
remove
Removes the animation related with key specified.
disable
Disables animations (typing keys would have no effect), and stops current ones.
enable
Enable animations (typing keys can start animations).

Related

Phaser 2 determining which unit is active

I have 3 clickable objects. When one is clicked, this becomes the 'selected unit'.
I am trying to create some generic actions for the units such as moving to a point.
In my create function I initialize the units, when a unit is clicked on - this is supposed to become the 'selected unit' so that my movement and direction function applies to the this unit. However, the script is not able to recognize which unit intend for example I get this error:
Uncaught TypeError: Cannot read property 'velocity' of undefined.
Is there a way to use a variable to indicate selected users and pass that to the functions?
window.onload = function() {
var block_count = 0;
var block = '';
var selected_unit = '';
var unit_clicked = 0;
var tank1 = null;
var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create, update: update, render: render});
function preload () {
game.load.image('block', 'block.png');
game.load.image('tank1', 'tank.png');
game.load.image('baddie', 'tank.png');
game.load.image('mouse_btn', 'block.png');
game.input.mouse.capture = true;
}
function create () {
game.physics.startSystem(Phaser.Physics.ARCADE);
mouse_btn = game.add.sprite(30,30, 'mouse_btn');
mouse_btn.anchor.setTo(0.5, 0.5);
//T1
tank1 = game.add.sprite(30,30, 'tank1');
initialise_player(tank1);
game.physics.enable(tank1, Phaser.Physics.ARCADE);
//T2
tank2 = game.add.sprite(30,60, 'tank1');
initialise_player(tank2);
game.physics.enable(tank2, Phaser.Physics.ARCADE);
game.world.setBounds(0, 0, 2000, 2000);
game.camera.follow(tank1);
}
function update () {
if(selected_unit == '') {
mouse_btn.x = game.input.mousePointer.worldX
mouse_btn.y = game.input.mousePointer.worldY
}
if(game.input.activePointer.leftButton.isDown && block_count == 0 && unit_clicked == 0) {
game.input.activePointer.leftButton.stop(event);
block_count =1;
block = game.add.sprite(game.input.mousePointer.worldX, game.input.mousePointer.worldY, 'block');
game.physics.enable(block, Phaser.Physics.ARCADE);
block.anchor.setTo(0.5, 0.5)
lookAtObject(selected_unit, block, 0.005);
}
if(block.alive){
game.physics.arcade.moveToObject(selected_unit, block, 260, 0)
} else {
console.log(selected_unit)
selected_unit.body.velocity.x = 0;
selected_unit.body.velocity.y = 0;
}
if(game.physics.arcade.collide(selected_unit, block)) {
block_count--;
block.kill();
}
}
function render(){
//console.log(game.physics.arcade.collide(tank1, block))
}
function lookAtObject(obj, target, rotspeed){
var angle = Math.atan2(block.y - tank1.y, block.x - tank1.body.x);
tank1.rotation = angle + game.math.degToRad(90);
}
function initialise_player(tank1){
tank1.anchor.setTo(0.5, 0.5);
tank1.inputEnabled = true;
tank1.input.useHandCursor = true;
tank1.events.onInputDown.add(t1_clicked,this);
tank1.events.onInputOver.add(t1_over, this)
tank1.events.onInputOut.add(t1_out, this)
}
function t1_clicked() {
selected_unit = tank1;
}
function t1_over() {
unit_clicked = 1
}
function t1_out () {
unit_clicked = 0
}
};
The error you're getting on initial load is because in update you're making an assumption that selected_unit exists and has a body.
Update your third if to make sure selected_unit is defined.
if (selected_unit !== '') {
selected_unit.body.velocity.x = 0;
selected_unit.body.velocity.y = 0;
}
However, a better option would be to put this a few lines down, where you kill the block instead.
if(game.physics.arcade.collide(selected_unit, block)) {
selected_unit.body.velocity.x = 0;
selected_unit.body.velocity.y = 0;
block_count--;
block.kill();
}
if (block.alive); moveToObject is also expecting selected_unit to exist and have a body, which may not be the case; wrap it with a check.
if (selected_unit !== '') {
game.physics.arcade.moveToObject(selected_unit, block, 260, 0)
}
That now allows tank1 to rotate to look at the item you just placed, but it doesn't move it until it or tank2 have been clicked on.
This also points out that there are a number of tweaks you'll want to make to your code in general, since you're ignoring arguments that are being passed in. For example, t1_clicked isn't using the sprite that's been clicked on, but is instead just hard-coding tank1. lookAtObject isn't using obj or target, but again has values hard-coded in.
One other thing you may want to change is the following:
if(selected_unit == '') {
mouse_btn.x = game.input.mousePointer.worldX
mouse_btn.y = game.input.mousePointer.worldY
}
If you make that the following, you won't end up with an extra sprite hanging about on the screen.
if (block_count === 0) {
mouse_btn.x = game.input.mousePointer.worldX;
mouse_btn.y = game.input.mousePointer.worldY;
}

How to save image location in localstorage

I have a question, currently i am trying to save a image location in the localstorage but i have no idea how to do that. I want it in localstorage because once you refresh the page i still want the image that you dragged, in the same spot as where you dragged the image to before the page refresh/reload. The script is like a inventory with items that are images.
This is the code:
const fill1 = document.querySelector('#item1');
const empties1 = document.querySelectorAll('#block1');
const empties2 = document.querySelectorAll('#block2');
const spot1 = document.getElementById("block1")
const spot2 = document.getElementById("block2")
checkSpot1()
checkSpot2()
localStorage.spot1 = 1
localStorage.spot2 = 0
// Fill listeners
fill1.addEventListener('dragstart', dragStart);
fill1.addEventListener('dragend', dragEnd);
// Loop through empty boxes and add listeners
for (const empty of empties1) {
empty.addEventListener('dragover', dragOver);
empty.addEventListener('dragenter', dragEnter);
empty.addEventListener('dragleave', dragLeave);
empty.addEventListener('drop', dragDrop);
}
for (const empty of empties2) {
empty.addEventListener('dragover', dragOver);
empty.addEventListener('dragenter', dragEnter);
empty.addEventListener('dragleave', dragLeave);
empty.addEventListener('drop', dragDrop);
}
// Drag Functions
function dragStart() {
this.idName += ' hold';
setTimeout(() => (this.idName = 'invisible'), 0);
}
function dragEnd() {
this.idName = 'fill1';
}
function dragOver(e) {
e.preventDefault();
}
function dragEnter(e) {
e.preventDefault();
this.idName += ' hovered';
}
function dragLeave() {
this.idName = 'empties1';
this.idName = 'empties2';
}
function dragDrop() {
this.idName = 'empties1';
this.idName = 'empties2';
this.append(fill1);;
}
function checkSpot1() {
if (localStorage.getItem("spot1") == 1) {
}
}
function checkSpot2() {
if (localStorage.getItem("spot2") == 1) {
}
}
spot1.addEventListener('dragend', setspot1)
spot2.addEventListener('dragend', setspot2)
function setspot1(){
localStorage.spot1 = 1
localStorage.spot2 = 0
}
function setspot2(){
localStorage.spot1 = 0
localStorage.spot2 = 1
}
But like i said i have no idea how i could store this in localstorage correctly, and make it display were the image was dragged to before the page reload.
If you want to save something to localStorage, it has to be in string format.
So, if you wanted to save spot one, it would look like:
localStorage.setItem("spot1", "0")
where "spot1" is the key and "0" would be the value.
To retrieve from localStorage:
localStorage.getItem("spot1")
This should return "0"
I would implement it like this: (this way you can get x and y coordinates of the dragged element):
// this is for storing -->
function dragOver(e) {
e.preventDefault();
// Get the x and y coordinates
var x = e.clientX;
var y = e.clientY;
// store the value in localStorage
window.localStorage.setItem('x',x);
window.localStorage.setItem('y',y);
}
// => same as JQuerys document.ready();
document.addEventListener("DOMContentLoaded", function(event) {
// read the data from localstorage
var x = window.localStorage.getItem('x');
var y = window.localStorage.getItem('y');
// Now you have to set the element position to the stored values
// I am assuming you want to set it for block1, and that block1 has absolute
// positioning
// only set the position if there is already a value stored
if( x && y )
{
// I found a pure Javascript solution now
document.getElementById("block1").style.left = x+"px";
document.getElementById("block1").style.top = y+"px";
}
});

How to use 'timeupdate' event listener to highlight text from audio?

I'm using the 'timeupdate' event listener to sync a subtitle file with audio.
It is working currently, but I'd like to adjust it to where it is just highlighting the corresponding sentence in a large paragraph instead of deleting the entire span and replacing it with just the current sentence. This is the sort of functionality I am trying to replicate: https://j.hn/lab/html5karaoke/dream.html (see how it only highlights the section that it is currently on).
This is made complicated due to timeupdate constantly checking multiple times a second.
Here is the code:
var audioSync = function (options) {
var audioPlayer = document.getElementById(options.audioPlayer);
var subtitles = document.getElementById(options.subtitlesContainer);
var syncData = [];
var init = (function () {
return fetch(new Request(options.subtitlesFile))
.then((response) => response.text())
.then(createSubtitle);
})();
function createSubtitle(text) {
var rawSubTitle = text;
convertVttToJson(text).then((result) => {
var x = 0;
for (var i = 0; i < result.length; i++) {
if (result[i].part && result[i].part.trim() != '') {
syncData[x] = result[i];
x++;
}
}
});
}
audioPlayer.addEventListener('timeupdate', function (e) {
syncData.forEach(function (element, index, array) {
if (
audioPlayer.currentTime * 1000 >= element.start &&
audioPlayer.currentTime * 1000 <= element.end
) {
while (subtitles.hasChildNodes()) {
subtitles.removeChild(subtitles.firstChild);
}
var el = document.createElement('span');
el.setAttribute('id', 'c_' + index);
el.innerText = syncData[index].part + '\n';
el.style.background = 'yellow';
subtitles.appendChild(el);
}
});
});
};
new audioSync({
audioPlayer: 'audiofile', // the id of the audio tag
subtitlesContainer: 'subtitles', // the id where subtitles should show
subtitlesFile: './sample.vtt', // the path to the vtt file
});

Change images randomly on click without repeating

I found this code on Stack Overflow: change images on click.
And it works for me. I want it to be random, but how can i prevent it from repeating the images. It should first repeat the images, when the user has clicked through all images.
I have made an JSfiddle with my code: http://jsfiddle.net/gr3f4hp1/
JQuery code:
var images = ["02.jpg","03.jpg","01.jpg"];
$(function() {
$('.change').click(function(e) {
var image = images[Math.floor(Math.random()*images.length)];
$('#bg').parent().fadeOut(200, function() {
$('#bg').attr('src', 'items/'+image);
$(this).fadeIn(200);
});
});
});
Keep track of the numbers that you have generated, and if its a repeat then get a new number.
You can Work Around This
var usedImages = {};
var usedImagesCount = 0;
function displayImage(){
var num = Math.floor(Math.random() * (imagesArray.length));
if (!usedImages[num]){
document.canvas.src = imagesArray[num];
usedImages[num] = true;
usedImagesCount++;
if (usedImagesCount === imagesArray.length){
usedImagesCount = 0;
usedImages = {};
}
} else {
displayImage();
}
}
you can try this code .
var images = ["02.jpg","03.jpg","01.jpg"];
var imagecon = [];
$(function() {
$('.change').click(function(e) {
if(images.length == 0) { // if no image left
images = imagecon; // put all used image back
imagecon = []; // empty the container
}
var index = Math.floor(Math.random()*images.length);
var image = images[index];
imagecon.push(image); // add used image
images.splice(index,1); // remove it to images
$('#bg').parent().fadeOut(200, function() {
$('#bg').attr('src', 'items/'+image);
$(this).fadeIn(200);
});
});
});
you could add a class to every image that appears like:
image.addClass("viewed")
and write an if statement that show the image only if it hasn't the class viewed:
if(!image.hasClass(viewed)){
(show the image methods);
image.addClass("viewed")
}
I'm not going to make all the code for you, just try this way, learn, fail, success, have fun! :D
Try this image change according to imgCnt variable.
var images = ["01.jpg","02.jpg","03.jpg","01.jpg"];
var imgCnt=1;
$(function() {
$('.change').click(function(e) {
// var image = images[Math.floor(Math.random()*images.length)];
if(imgCnt >= images.length){
imgCnt=0;
}
var image =images[imgCnt];
// alert(image);
$('#bg').parent().fadeOut(200, function() {
$('#bg').attr('src', 'items/'+image);
$(this).fadeIn(200);
imgCnt++;
});
});
});
Demo
There are lots of method here i just push the value of visited image in to Visited array
Campate two array show only differ element
var images = ["02.jpg","03.jpg","01.jpg"];
var visited = [];
$(function() {
$('.change').click(function(e) {
var image = images[Math.floor(Math.random()*images.length)];
visited.push(image);
$('#bg').parent().fadeOut(200, function() {
y = jQuery.grep(images, function(value) {
if(jQuery.inArray(value, visited) == -1){
$('#bg').attr('src', 'items/'+image);
$(this).fadeIn(200);
}
});
} });
});
});
I hopes its help

Why are my properties losing definition? (JS)

I'm creating a drag/drop heavy page and giving each draggable element defaultTop and defaultLeft properties so that I can easily reset it to it's original position. This was fine and unremarkable until suddenly, the reset function reports their values as undefined. Since I wasn't working on these pieces when it broke (they've been working for some time) I'm not sure where I've gone wrong. Thanks for the help.
The function that creates the element is:
function makeTool(id, imgURL, defaultL, defaultT,trayname){
var a=document.createElement('img');
a.setAttribute('src', imgURL);
a.setAttribute('id',id);
a.setAttribute('class','drag');
a.intray=true;
a.tray=trayname;
a.rotation=0;
a.style.zIndex=document.getElementById(trayname).style.zIndex+1;
document.getElementById(trayname).appendChild(a);
a.defaultTop=ExtractNumber(document.getElementById(trayname).style.top)+defaultT;
a.defaultLeft=ExtractNumber(document.getElementById(trayname).style.left)+defaultL;
a.style.top=a.defaultTop+'px';
a.style.left =a.defaultLeft+'px';
a.addEventListener('touchstart', function(e) { return self.touchStart(e) }, false);
a.addEventListener('gesturestart', function(e) { return self.gestureStart(e) }, false);
a.addEventListener('touchmove', function(e) { return self.touchMove(e) }, false);
a.addEventListener('touchend', function(e) { return self.touchEnd(e) }, false);
tools.push(a);
return a;
}
and the reset function is:
function reposition(t){
console.log(t+' top: '+document.getElementById(t).defaultTop);
document.getElementById(t).style.left=document.getElementById(t).defaultLeft+'px';
document.getElementById(t).style.top=document.getElementById(t).defaultTop+'px';
}
which is where I'm getting the log of undefined
I'm not sure if thar helps, but I had a similar problem.
I was writing a object to calculate de width of my DIVs accordingly to my innerWidth:
function ScreenGrid() {
'use strict';
this.ColumnIDs = new Array();
this.Widths = new Array();
this.Dynamic = true;
this.Set = adjust;
var ColumnIDsPersist;
var WidthsPersist;
function adjust() {
//stuff
for (var i = 0; i < ColumnIDsPersist.length; i++) {
The adjust function is where de magic happends. To ensure that the DIVs would keep fitted in the screen I used the following code:
if (window.addEventListener) {
// Good browsers.
window.addEventListener('resize', react, false);
}
else if (w.attachEvent) {
// Legacy IE support.
window.attachEvent('onresize', react);
}
else {
// Old-school fallback.
window.onresize = react;
}
And this is the react function:
// Slight delay.
function react() {
// Clear the timer as window resize fires,
// so that it only calls adapt() when the
// user has finished resizing the window.
clearTimeout(timer);
// Start the timer countdown.
timer = setTimeout(adjust, 16);
// -----------------------^^
// Note: 15.6 milliseconds is lowest "safe"
// duration for setTimeout and setInterval.
//
// http://www.nczonline.net/blog/2011/12/14/timer-resolution-in-browsers
}
The problem was the every time REACT fires, o got undefined in this.ColumnIDs. After a lot o investigation i noticed that when I fired the ADJUST from SET() the object THIS was my SCREENGRID, but when I fired from REACT it becames the WINDOW, so I got undefined in this.ColumnIDs.
I solved with this code:
function ScreenGrid() {
'use strict';
this.ColumnIDs = new Array();
this.Widths = new Array();
this.Dynamic = true;
this.Set = adjust;
var ColumnIDsPersist;
var WidthsPersist;
function adjust() {
// This clearTimeout is for IE.
// Really it belongs in react(),
// but doesn't do any harm here.
clearTimeout(timer);
// Parse browser width.
var _width = window.innerWidth || window.document.documentElement.clientWidth || window.document.body.clientWidth || 0;
var _heigth = window.innerHeight || window.document.documentElement.clientHeight || window.document.body.clientHeight || 0;
var _usedWidth = 0;
var _fluidColumn = null;
//Ao chamar a função adjust novamente no evento on resize, o objeto THIS deixa de ser a função e passa a ser a janela,
//Essas vareáveis garantem a persistencia dos dados a serem utilizados.
ColumnIDsPersist = (typeof ColumnIDsPersist == 'undefined') ? this.ColumnIDs : ColumnIDsPersist;
WidthsPersist = (typeof WidthsPersist == 'undefined') ? this.Widths : WidthsPersist;
for (var i = 0; i < ColumnIDsPersist.length; i++) {
Well, that's it, I hope it helps!

Categories

Resources