Javascript create an image and make it move - javascript

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!

Related

How do you restate setInterval after clearInterval has already been declared?

I realize there are more than a few answers on here about this but this particular instance has a very individual problem. I need to, on click, replay this png sequence after clearInterval has been used.
var myImage = document.getElementById("myImage");
var animationArray = ['assets/calvin_hobbes_dance00.png',
'assets/calvin_hobbes_dance01.png',
'assets/calvin_hobbes_dance02.png',
'assets/calvin_hobbes_dance03.png',
'assets/calvin_hobbes_dance04.png',
'assets/calvin_hobbes_dance05.png',
'assets/calvin_hobbes_dance06.png',
'assets/calvin_hobbes_dance07.png',
'assets/calvin_hobbes_dance08.png',
'assets/calvin_hobbes_dance09.png',
'assets/calvin_hobbes_dance10.png'];
var animationIndex = 0;
function changeImage () {
myImage.setAttribute("src", animationArray[animationIndex]);
animationIndex++;
if (animationIndex >= animationArray.length) {
animationIndex = 10;
clearInterval(intervalHandler);
}
}
var intervalHandler = setInterval(changeImage, 100);
A secondary question, this is merely a code sample. How might I wrap this so I can use it for elements that have animations attached that when upon focus play the animation?
Thank you.
Just add an onclick handler to your image. In the onclick handler, reset the animationIndex to 0, call clearInterval to clear the interval if it is running, and call the setInterval function again.
var myImage = document.getElementById("myImage");
var animationArray = ['assets/calvin_hobbes_dance00.png',
'assets/calvin_hobbes_dance01.png',
'assets/calvin_hobbes_dance02.png',
'assets/calvin_hobbes_dance03.png',
'assets/calvin_hobbes_dance04.png',
'assets/calvin_hobbes_dance05.png',
'assets/calvin_hobbes_dance06.png',
'assets/calvin_hobbes_dance07.png',
'assets/calvin_hobbes_dance08.png',
'assets/calvin_hobbes_dance09.png',
'assets/calvin_hobbes_dance10.png'];
var animationIndex = 0;
function changeImage () {
myImage.setAttribute("src", animationArray[animationIndex]);
animationIndex++;
if (animationIndex >= animationArray.length) {
animationIndex = 10;
clearInterval(intervalHandler);
}
}
myImage.onclick = function() {
animationIndex = 0;
clearInterval(intervalHandler);
intervalHandler = setInterval(changeImage, 100);
};
var intervalHandler = setInterval(changeImage, 100);
To answer your secondary question, you might want to consider another approach because this could get kind of messy and be hard to maintain in the future. Consider learning how to do animations using HTML canvas. Here is a tutorial I found showing how you could create multiple animations: http://www.williammalone.com/articles/create-html5-canvas-javascript-sprite-animation/
In fact, I would advise to change your implementation to use the canvas instead.

Manual traffic light conversion into automatic via Javascript

I am trying to do a traffic light sequence which runs on a timed basis automatically without user input . I have now got the code working but it only runs through once and then stops so how can I change this so it keeps going? Here is my code:
<!DOCTYPE html>
<html>
<head>
<script>
var images = new Array()
images[0] = "image2.jpg";
images[1] = "image3.jpg";
images[2] = "image4.jpg";
setInterval("changeImage()", 3000);
var x=0;
function changeImage()
{
document.getElementById("img").src=images[x]
x++;
}
</script>
</head>
<body>
<img id="img" src="image1.jpg">
</body>
</html>
To make this automatic, you can either put it in a loop, or you can use the setInterval function.
var interval = setInterval(nextLightClick, 1500);
This will loop indefinitely, running the function every 1500 milliseconds (1.5 seconds). If you want to stop it, you can simply say:
clearInterval(interval);
Here's an example -- note that I am changing the innerHTML, rather than the src, and I am using a div instead of image, but the logic will be exactly the same.
var tlight = new Array("1green.jpg","2yellow.jpg","3red.jpg");
var index = 0;
var tlightLen = tlight.length;
var image = document.getElementById('firstlight');
image.innerHTML = tlight[index];
var interval;
function startInterval() {
interval = setInterval(nextLightClick, 1500);
}
function stopInterval() {
clearInterval(interval);
}
function nextLightClick() {
index++;
if (index == tlightLen)
index = 0;
image.innerHTML = tlight[index];
}
<span id="firstlight"></span></br>
<button onclick="startInterval()">Start</button>
<button onclick="stopInterval()">Stop</button>

Canvas - image opacity loop (fade in)

guys. here is a bit of code that is supposed to be okay, though it doesn't work...heh...quite typical =)
function xxx() {
var txtCanvas = document.getElementById('text');
var textOne = txtCanvas.getContext('2d');
var alpha = 0.5;
textOne.globalAlpha = alpha;
// loading image
var img = new Image();
img.src = "http://tvangeste.com/gallery/selani/tv4_2.jpg"
img.onload = function () {
textOne.drawImage(img, 0, 0);
}
//end of image loader
if (alpha < 1)
{
alpha += 0.1;
}
}
requestAnimationFrame(xxx);
This is Fiddle to show how it doesn't work...
http://jsfiddle.net/gLs1owd6/
The script is supposed to do one simple thing - to fade in the image.
Any suggestions? Thanks!
You need a loop to be able to redraw the image at various opacity levels. For a loop you need something that doesn't block UI as well as refreshing with each monitor update, so, requestAnimationFrame to the rescue.
Here is one way to go about this:
var img = new Image();
img.onload = function () {
// when image has loaded we can use it.
// this is a self-invoking function used to fade in the image
(function loop() {
// we can update the property directly
textOne.globalAlpha += 0.01;
// as we have opacity involved we need to clear the canvas each time
textOne.clearRect(0, 0, txtCanvas.width, txtCanvas.height);
// redraw the image
textOne.drawImage(img, 0, 0);
// if not full opacity, loop (canvas will clamp the value for us)
if (textOne.globalAlpha < 1.0) {
requestAnimationFrame(loop);
}
else {
// when done, call the next step from here...
}
})();
}
// set source as last step for image loading
img.src = "http://tvangeste.com/gallery/selani/tv4_2.jpg"
Modified fiddle
Hope this helps!

How to add prev and next button in slide show

I just made this program for slide show it is working well but i want to use previous and next buttons in the slide show and i don't have any idea how to do that so i put this here please help for the same
var image1=new Image()
image1.src="slide/23.jpg"
var image2=new Image()
image2.src="slide/7.jpg"
var image3=new Image()
image3.src="slide/4.jpg"
var image4=new Image()
image4.src="slide/5.jpg"
var image5=new Image()
image5.src="slide/6.jpg"
</script>
<img id="myImg"src="slide/2.jpg" name="img" width="1000" height="250"/>
<script>
var step=1
function slideImages(){
if (!document.images)
return
document.images.img.src=eval("image"+step+".src")
if (step<5)
step++
else
step=1
setTimeout("slideImages()",3000)
}
slideImages()
</script>
You probably want to abstract away some code so it can be easily reused in your functions:
// Dealing with the counter:
var step;
var steps = 5;
function increment() {
s = (s + 1) % steps;
}
function decrement() {
s--;
if (s<0) s = steps-1;
}
// Dealing with the slide show:
function show() {
document.images.img.src=eval("image"+step+".src")
}
function next() {
increment();
show();
}
function prev() {
decrement();
show();
}
// Automatic sliding:
window.setInterval(next, 3000);
Also, i would reconsider your approach to storing images:
function createImgBySource(src){
var img = new Image();
img.src = src;
return img;
}
var images = [
createImgBySource('slide/23.jpg'),
createImgBySource('slide/7.jpg'),
createImgBySource('slide/4.jpg'),
createImgBySource('slide/5.jpg'),
createImgBySource('slide/6.jpg')
];
Now you can change the increment and decrement functions to use images.length instead of steps, so you can add more images without having to alter other variables. Also, your show() function should look like this (getting rid of the nasty eval):
function show() {
document.images.img.src = images[step];
}
Try the below code
var ss = new TINY.fader.init("ss", {
id: "slides", // ID of the slideshow list container
position: 0, // index where the slideshow should start
auto: 0, // automatic advance in seconds, set to 0 to disable auto advance
resume: true, // boolean if the slideshow should resume after interruption
navid: "pagination", // ID of the slide nav list
activeClass: "current", // active class for the nav relating to current slide
pauseHover: true, // boolean if the slideshow should pause on slide hover
navEvent: "click", // click or mouseover nav event toggle
duration: .25 // duration of the JavaScript transition in seconds, else the CSS controls the duration, set to 0 to disable fading
});
got from Here also here is a sample Fiddle
I would consider using something like jCarousel.
I think you are best putting all of your images into an array and then looking over it. I am assuming that the image tag with the ID 'myImg' is the one that you want to update, as such you should use document.getElementByID('myImg') and not document.images.img.src=eval("image"+step+".src") -- eval should also be avoided as the performance is poor and it can be dangerous.
Put this as the end of your page:
<script type="text/javascript">
(function(){
var step = 0;
var images = [image1, image2, image3, image4, image5];
var image = document.getElementByID('myImg');
var slideImages = function() {
image.src = images[step].src;
step++;
if (step == images.length){
step == 0;
}
setTimeout("slideImages()", 3000);
};
slideImages()
})();
</script>

2 or more async requests in javascript to load image or do anything else

Single request and response model at one time do not utilizes full network/internet bandwidth, thus resulting in low performance. (benchmark is of half speed utilization)
how to make this code use 2 or 3 or more async requests instead of one.(ajax)
or do i need multi threading? and is it possible in javascript?
(this is for making a video out of an ip )
every time the image changes on request. and yes i need to be async with multiple fetch requests (not single as i explained above) or you recomend threads?
<html>
<head> <script language="JavaScript">
// Global vars
img = 'http://pastebin.com/i/t.gif';
timeout = 1000;
next = 0;
function onLoad( ) {
setTimeout( 'reloadImage( )', timeout );
}
// Reloader
function reloadImage( ) {
next = ( new Date( ) ).getTime( ) + timeout;
document.images.dv.src = img + "?" + next;
}
</script>
</head>
<body>
<img src="img" name="dv" onLoad="onLoad( )">
</body>
</html>
and
<html>
<head>
</head>
<body>
<div id="container"></div>
<script language="JavaScript">
var canLoad = true;
var container = document.getElementById("container");
var image = document.createElement("img");
image.onload = function() {
canLoad = true;
console.log("Image reloaded.");
}
var imageUrl = "http://url/snapshot.jpg";
var fps = 2;
container.appendChild(image);
function loadImage() {
if (canLoad) {
canLoad = false;
var str = new Date().getTime();
image.setAttribute("src", imageUrl + "?" + str);
console.log("Reloaded now.");
} else {
console.log("Can't reload now.");
}
}
setInterval(loadImage, fps); // 30 fps
</script>
</body>
</html>
Not actually tested, and I think it'll very likely to cause a "stack overflow" eventually (if you directly implement it), but you may still give it a look:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
(function(){
var img="/*url*/";
var interval=50;
var pointer=0;
function showImg(image,idx)
{
if(idx<=pointer) return;
document.body.replaceChild(image,document.getElementsByTagName("img")[0]);
pointer=idx;
preload();
}
function preload()
{
var cache=null,idx=0;;
for(var i=0;i<5;i++)
{
idx=Date.now()+interval*(i+1);
cache=new Image();
cache.onload=(function(ele,idx){return function(){showImg(ele,idx);};})(cache,idx);
cache.src=img+"?"+idx;
}
}
window.onload=function(){
document.getElementsByTagName("img")[0].onload=preload;
document.getElementsByTagName("img")[0].src="/*initial url*/";
};
})();
</script>
</head>
<body>
<img />
</body>
</html>
What it does:
When the initial image loads, preload() is called;
When preload() is called, it creates 5 image cache, and each attach its onload event to showImg();
When showImg() is called, it checks whether the current index is behind current pointer, and if it does, replace the current image with this new one, and call preload();
Back to 2.
If you really going to implement this, increase interval and decrease i<5. Also, a caching/queuing mechanic to check how many images in cache/queue before loading the next queue would be nice.
Also, notice that I didn't use getElementById to get the image, because there will be no stable ID.

Categories

Resources