Javascript play button for animation - javascript

I have a Javascript animation using Raphael which is in an external file linked to HTML. I would like to have the user click on the animation to start it rather than the animation starting as soon as the page is loaded.
window.addEventListener("load",function(){
var paper = new Raphael(document.getElementById("animation"), 800, 600);
var img = paper.image("backimg.jpg",0,0,950,600);
img.attr({"clip-rect":"0,0,800,600"});
img.addEventListener("click",function() {
var squ = paper.rect(-100,50,100,100);
squ.attr("fill", "#ffffff");
squ.animate({transform: "T450,0"}, 2000, "ease-out", explode);
var cir2 = paper.rect(400,100,1,1);
function explode(){
cir2.attr("fill","#f00");
cir2.animate({ transform:'s100' }, 2000);
}
});
});

Thank you OP for providing the code. The Raphael JS library uses SVG so the only applicable solution is to set a click event listener to the parent node which, in this case, it the element with an id of animation.
Examine the code snippet:
//https://www.w3schools.com/css/img_fjords.jpg
window.addEventListener("load",function(){
var animation = document.getElementById('animation');
var paper = new Raphael(animation, 800, 600);
var img = paper.image("https://www.w3schools.com/css/img_fjords.jpg",0,0,950,600);
img.attr({"clip-rect":"0,0,800,600"});
animation.addEventListener("click",function() {
var squ = paper.rect(-100,50,100,100);
squ.attr("fill", "#ffffff");
squ.animate({transform: "T450,0"}, 2000, "ease-out", explode);
var cir2 = paper.rect(400,100,1,1);
function explode(){
cir2.attr("fill","#f00");
cir2.animate({ transform:'s100' }, 2000);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.2.7/raphael.js"></script>
<div id="animation"></div>
Hopefully this is helpful.

if you want doing it using a button it should look like this:
<button onclick="myAnimation()">Play Animation</button>
where myAnimation is the name of the function that runs the animation.

Related

Performance jQuery Ajax load game sources display as modal

I have a base website system which is using ajax load content without refreshing pages. I have a game page that load many html5 game links via ajax json and when I click on any games it will load the game source files which display as pop up. I am wonder while I'm playing then if I click the close button for stopping the game and then I remove the element of the source files game. Will it free up the memory? As I have noticed, it seems to getting slow the broswer. Anyone has experienced with that, please share with me.
Note: I need some suggestions in order to remove the elements and free up the memory.
eg:
<div id="pop-up">
<a id="close" href="#">Close Button</a>
<div id="inner-pop-up">
<script src="game sources" type="text/javascript"></script>
<script src="game sources" type="text/javascript"></script>
<script src="game sources" type="text/javascript"></script>
<div id="game">
<canvas></canvas>
</div>
</div>
</div>
$('#pop-up').modal('view', {
speed: 750,
close: '.close-favourite',
easing: 'easeOutBounce',
animation: 'top',
position: 'center',
overlayClose: true
});
$('#close').on('click', function() {
$('#inner-pop-up').children().remove();
});
The only real way to free up any resources used by script functions is to add a JavaScript file that basically calls delete window.myFunction for every possible object and function (functions are objects really) your specified script files may define. To me, for obvious reasons, this is a really bad idea.
Note that these objects would be script (window) objects so you cannot use .remove() to remove those.
I would also note that your should use $('#inner-pop-up').empty(); rather than your $('#inner-pop-up').children().remove(); since that would remove the text of the element if any, as well and specifically removes the data and event handlers from those elements prior to removal from the DOM.
You might have some very specific functions and objects from your scripts that you might want to remove here but only the contents of your scripts would tell that. If you create global window objects that gets really messy fast.
Note it is REALLY hard to determine what a script file creates and then remove it.
To prove a point open up your favorite browser console and execute $("script").remove(). stuff in that script still runs.
Eg: This is my game file which contained the object like that
FootballChallenge.Game = function (game) {
FootballChallenge._scoreText = null;
FootballChallenge._score = 0;
FootballChallenge.kickBoard;
this._preventClick = true;
FootballChallenge.kaboomGroup;
FootballChallenge.ball;
FootballChallenge.shoe;
FootballChallenge.self;
};
FootballChallenge.Game.prototype = {
create: function () {
FootballChallenge.self = this.game;
this.game.physics.startSystem(Phaser.Physics.ARCADE);
this.game.physics.arcade.checkCollision.up = false;
this.bg = this.game.add.image(this.game.world.centerX, this.game.world.centerY, 'field');
this.bg.anchor.setTo(0.5);
FootballChallenge.kickBoard = this.game.add.sprite(10, 20, 'kickBoard');
FootballChallenge._scoreText = this.game.add.bitmapText(0, FootballChallenge.kickBoard.height/2 + 20, 'white-font', ''+FootballChallenge._score+'', 32);
FootballChallenge._scoreText.align = 'center';
FootballChallenge._scoreText.x = (FootballChallenge.kickBoard.width-FootballChallenge._scoreText.width + 20)/2;
FootballChallenge.ball = this.game.add.sprite(this.game.world.centerX, this.game.world.centerY - 100, 'ball');
this.game.physics.arcade.enable(FootballChallenge.ball);
FootballChallenge.ball.anchor.setTo(0.5);
FootballChallenge.ball.scale.setTo(0.5);
FootballChallenge.ball.body.collideWorldBounds = true;
FootballChallenge.ball.body.gravity.y = 0;
FootballChallenge.ball.body.bounce.setTo(1);
FootballChallenge.shoe = this.game.add.sprite(this.game.world.centerX, this.game.world.centerY, 'shoe');
this.game.physics.arcade.enable(FootballChallenge.shoe);
FootballChallenge.shoe.anchor.setTo(0.5);
FootballChallenge.shoe.scale.setTo(0.5);
FootballChallenge.shoe.body.setSize(130,50,0,20);
FootballChallenge.shoe.body.collideWorldBounds = true;
FootballChallenge.kaboomGroup = this.game.add.group();
FootballChallenge.kaboomGroup.createMultiple(10, 'kaboom');
FootballChallenge.kaboomGroup.forEach(this.explosion, this);
this.play();
},
explosion: function(kick) {
kick.anchor.x = 0.7;
kick.anchor.y = 0.5;
kick.animations.add('kaboom');
},
play: function() {
this.bitmask = this.game.make.bitmapData(this.game.width, this.game.height);
this.bitmask.fill(50,50,50);
this.mask = this.game.add.sprite(0, 0, this.bitmask);
this.mask.tint = 0x000000;
this.mask.alpha = 0.6;
this.game.paused = true;
var pausedText = this.game.add.bitmapText(this.game.world.centerX, this.game.world.centerY - 200, 'white-font', 'click anywhere to begin!', 32);
pausedText.align = 'center';
pausedText.tint = 0xff0e25;
pausedText.anchor.setTo(0.5);
this.game.input.onDown.add(function(){
pausedText.destroy();
this.game.paused = false;
this.mask.alpha = 0;
FootballChallenge.ball.body.gravity.y = 1500;
this.game.canvas.style.cursor = "none";
}, this);
},
countScore: function(ball, shoe) {
ball.body.velocity.y = -1000;
ball.body.gravity.x = FootballChallenge.self.rnd.integerInRange(-80, 80);
FootballChallenge._scoreText.setText(FootballChallenge._score +=1);
FootballChallenge._scoreText.x = (FootballChallenge.kickBoard.width-FootballChallenge._scoreText.width + 20)/2;
var boom = FootballChallenge.kaboomGroup.getFirstExists(false);
boom.reset(shoe.x, shoe.y);
boom.play('kaboom', 40, false, true);
},
lose: function() {
this.game.state.start('EndGame');
},
update: function() {
if(FootballChallenge.ball.y >= this.game.height - 100) {
FootballChallenge.ball.body.gravity = false;
this.game.time.events.add(Phaser.Timer.SECOND * 0.2, this.lose, this);
}
this.game.physics.arcade.collide(FootballChallenge.ball, FootballChallenge.shoe, this.countScore);
this.game.physics.arcade.moveToPointer(FootballChallenge.shoe, 30, this.game.input.activePointer, 50);
}
};

Javascript create an image and make it move

I'm trying to make a little browser game where you can shoot bullets.
Right now I am able to make a bullet, but I don't know how to get in moving.
I have done this:
var bullet_id = 1;
var timer_id; // reference of the timer, needed to stop it
var speed = 350; // pixels/second
var period = 10; // milliseconds
var sprite; // the element that will move
var sprite_speed = 0; // move per period
var sprite_position = 315; // pixels
function createbullet() {
var img = document.createElement("img");
img.src = "images/bullet.png";
img.id = "bullet";
img.name = "bullet";
var foo = document.getElementById("fooBar");
foo.appendChild(img);
move(1);
bullet_id++;
}
function animate ()
{
document.getElementById("bullet").style.left=340 + "px";
sprite_position += sprite_speed;
sprite.style.left = sprite_position+'px';
}
function move(direction)
{
if (timer_id) stop();
sprite_speed = speed * period/1000 * direction;
timer_id = setInterval (animate, period);
}
function stop()
{
clearInterval (timer_id);
timer_id = null;
}
function init()
{
sprite = document.getElementById ("bullet"); // the HTML element we will move
animate(); // just to initialize sprite position
}
window.onload = init; // start doing things once the page has loaded */
I tried to add a bullet_id system but I couldn't get it working really.
Here is my html
<a onmousedown="document.jack.src=image2.src;" onmouseup="document.jack.src=image1.src;" onclick="createbullet()"><img id="jack" name="jack" src="/images/jack1.png" /></a>
<div id="fooBar"></div>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
document.getElementById('jack').addEventListener('click',function(){...})
Ok so maybe I didn't think that one through, have just designed one to see if I could and it works, hope it helps:
/********************************************************/
stg=0
bgx=0
spd=70
buls=0
act=false
/********************************************************/
function ani(){
var int
act=true
bgx-=52
stg++
$('#jack').css('background-position','-52px 0px')
int=setInterval(function(){
if(stg<4){bgx-=52; stg++}
else{ bgx=0; stg=0 }
$('#jack').css('background-position',bgx+'px 0px')
if(stg==4) new Bullet();
if(!stg){
act=false
clearInterval(int)
}
},spd)
}
/********************************************************/
function Bullet(){
var x,img,int
x=52
img=document.createElement('img')
img.src='bullet.png'
img.setAttribute('class','mh posAbs')
img.setAttribute('style','top:0px;left:'+x+'px')
img.setAttribute('id','bul'+buls)
scre.appendChild(img)
img=document.getElementById('bul'+buls)
buls++
int=setInterval(function(){
if(x<300){
x+=13
img.setAttribute('style','top:0px;left:'+x+'px')
}
else{
img.src='exp.png'
clearInterval(int)
setTimeout(function(){ scre.removeChild(img) },100)
}
},spd)
}
/********************************************************/
$(document).ready(function(){
$('html').keydown(function(){
if(!act){
if(event.keyCode==13) ani();
}
})
$('html').click(function(){
if(!act) ani();
})
})
/********************************************************/
<div id="scre" class="posRel">
<div id="jack"></div>
</div>
<style>
#jack{
width:52px;
height:37px;
background:url('02.png') no-repeat;
background-position:0px 0px;
background-size:auto 100%
}
</style>
Ok so what's happening above is every time you click or press Enter, the firing animation is called, which is animated in stages and when it gets to a certain stage it calls upon the Bullet() constructor to create a new Object or bullet.
While creating the bullet, the constructor generates an <img> and gives it a unique id based upon the buls variable, which is then incremented to keep the id's unique.
This is the most important part:
img=document.getElementById('bul'+buls)
It will NOT work without it as any references to img in the code after it will refer to the last img created and not say:- 'bullet 5 of 10 that are on screen'.
Once created the Bullet object handles the movement of the image it is referenced to, removing the need to move it with any other code...
P.S. The $('html').keydown(...) acts as an auto-fire!

Javascript class on path element

I'm creating a interactive map with svg and I have converted the svg format to a javasript file (rahpael). I want to put a class on a path element, to create a hover effect, but I can't seem to get it to work:
var path_cz = rsr.path("M513.4,537l-329,19.3L209.5,666c0,0,9.5,36.8,51.5,48.8l108,22.7c13.3-16.7,119-43.4,175.6-8.7l165.7-58.6 c0,0,210.2-54.5,113.6-150.5c-33.3-27.3-61.9-50.4-61.9-50.4l-72.8-5.5l-46.9,2l-154,6.7l-2.6,21L513.4,537z").attr({fill: '#4F217C',parent: 'farver','stroke-width': '0','stroke-opacity': '1'}).data('id', 'path_cz');
I've tried .attr("class","classname"); and some other stuff inside .attr, but still nothing..
Any suggestions would be appreciated, thx :)
As you are using Raphael JS, the easiest way to do this is to hook into the hover method that Raphael supplies out of the box and update it that way.
$(document).ready(function() {
var rsr = Raphael(0, 0, 1000, 1000);
var path_cz = rsr.path("M513.4,537l-329,19.3L209.5,666c0,0,9.5,36.8,51.5,48.8l108,22.7c13.3-16.7,119-43.4,175.6-8.7l165.7-58.6 c0,0,210.2-54.5,113.6-150.5c-33.3-27.3-61.9-50.4-61.9-50.4l-72.8-5.5l-46.9,2l-154,6.7l-2.6,21L513.4,537z").attr({fill: '#4F217C',parent: 'farver','stroke-width': '0','stroke- opacity': '1'}).data('id', 'path_cz');
path_cz.hover(function() {
path_cz.node.setAttribute('class', 'one');
}, function() {
path_cz.node.setAttribute('class', 'two');
});
});
For an example, here is a fiddle: http://jsfiddle.net/n9Mt6/1/

Calling js functions at same time yui

currently this is causing the (image) fadeout function to end, and then the fade in function fires. i need the images to crossfade and the opacity of each image to overlap. im having trouble getting this work. thoughts?
_initFade: function () {
this._timer = Y.later(this._intervalDuration, this, this._startPeriod, [], false);
},
_startPeriod: function () {
this._timer = Y.later(this._intervalDuration, this, this._fadeOut, [], true);
this._fadeOut();
},
_fadeOut: function(){
var host = this.get('host');
this._animOut.set('node', host._getCurrentBlock());
this._animOut.once('end', this._fadeIn, this);
this._animOut.run();
},
_fadeIn: function(){
var host = this.get('host'),
blocks = host.get('blocks'),
index = host.get('index');
index = host._moveIndex(host._getNextIndex());
var nextBlock = blocks.item(index);
this._transparent(nextBlock);
host.syncUI();
this._animIn.set('node', nextBlock);
this._animIn.run();
},
YUI doesn't support multiple animations which run in sync. But have a look at the 'tween' event of Y.Anim. It is called for every frame of the animation. So you can fade one image using the animation and adjust the opacity of the second image during the tween event.
For example, I use the tween event to animate multiple items simultaneously:
var someNode = Y.Node.create("<div></div>"); // invisible div to animate
Y.one(document.body).appendChild(someNode);
var anim = new Y.Anim({
node: someNode,
duration: 0.25,
from: { color: 'red' },
to: { color: 'white' }
});
anim.on('tween', function(event){
Y.StyleSheet().set('input.text.error', { backgroundColor: someNode.getStyle('color') });
// other animations
});

Restarting animated Gif

I want to put a timer onto my gallery rotation script. This timer is a circular animated gif. i want it to start again when a new image loads..
I would have thought that this would work but apparently not.
// Loader needs to be a Global
loader = new Image();
loader.id = "loader_graphic";
loader.src = "images/loader.gif";
var $container = $('#slider .imgs').cycle({
fx: 'scrollHorz',
speed: 1000,
timeout: 5000,
before : function() {
resetLoader();
}
});
function resetLoader() {
$("#loader_graphic").remove();
$("#loader").append(loader);
}
Does anyone have any ideas on fixing this. If this cannot work, does anyone know how to achieve this effect?
Your javascript code doesn't recreate the variable when resetting, perhaps setting the variable to a newly created dom element would work?
// Loader needs to be a Global
var loader = newLoaderImage();
var $container = $('#slider .imgs').cycle({
fx: 'scrollHorz',
speed: 1000,
timeout: 5000,
before : function() {
resetLoader();
}
});
function newLoaderImage() {
i = new Image();
i.id = "loader_graphic";
i.src = "images/loader.gif";
return i;
}
function resetLoader() {
$("#loader_graphic").remove(); // or loader.remove();
loader = newLoaderImage();
$("#loader").append(loader);
}
Maybe you can use a workaround with JavaScript but restarting is an option for a gif image, it would be simpler to modify it (with gimp eg.).
One approach might be to use two images: one animated gif, and a static gif that shows the "stopped" frame of the animation.
Position them in the same place. When the image is loading, you show the animated gif (probably using visibility:visible; and hide the stopped one, using visibility: hidden;. When you need the animation to stop, hide the animated gif, and show the stopped image.

Categories

Resources