Add dynamically a gif image with animation - javascript

I'm trying to load programmatically an img with a .gif extension. But the animation only happens once.
How can I add more img and see the animation every time I add a new img, not just the final state?
Note: I do not want a loop gif. I just want the next img to behave just like the first, animate then stop.
var topval = 10;
var right = 10;
var addStar = function() {
var img = $('<img id="'+topval+'">');
img.attr('src','https://s3-sa-east-1.amazonaws.com/musicamise/astronautAnimatedGif.gif');
img.attr('alt','alt'+topval);
img.css('position','absolute');
img.css('right', right+'px');
img.css('top', topval+'px');
img.appendTo('body');
topval = topval+10;
right = right+10;
};
$("#addStar").click(addStar);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body style="margin:0;padding:0;">
<button id="addStar">Click do add</button>
</body>
Thanks in advance.

You can hack around this problem by appending a random query string parameter to the URL. This tricks the browser into thinking the image is different each time. For example:
https://s3-sa-east-1.amazonaws.com/musicamise/astronautAnimatedGif.gif?x=' + Math.random()
var topval = 10;
var right = 10;
var addStar = function(){
var img = $('<img id="'+topval+'">');
img.attr('src','https://s3-sa-east-1.amazonaws.com/musicamise/astronautAnimatedGif.gif?x=' + Math.random());
img.attr('alt','alt'+topval);
img.css('position','absolute');
img.css('right', right+'px');
img.css('top', topval+'px');
img.appendTo('body');
topval = topval+10;
right = right+10;
}
$("#addStar").click(addStar);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body style="margin:0;padding:0;">
<button id="addStar">Click do add</button>
</body>
Thanks in advance.

Your problem is because the browser takes the same cache image. When you change the URL of the image, it's like you're looking for another image. The downside of this is that he always makes a new request for the image.
var topval = 10;
var right = 10;
var count = 0;
var addStar = function(){
var img = $('<img id="'+topval+'">');
img.attr('src','https://s3-sa-east-1.amazonaws.com/musicamise/astronautAnimatedGif.gif?count='+count++ );
img.attr('alt','alt'+topval);
img.css('position','absolute');
img.css('right', right+'px');
img.css('top', topval+'px');
img.appendTo('body');
topval = topval+10;
right = right+10;
}
$("#addStar").click(addStar);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body style="margin:0;padding:0;">
<button id="addStar">Click do add</button>
</body>

create a div
set your gif as a background image of your div:
$('myDiv').css('background-image', 'url(' + imageUrl + ')');

Related

Javascript display dynamic changing image

I want to refresh an image every 1 second. This picture is dynamically generated by my webcam, but this script sometimes display broken images when browser didnt yet load a picture before display. How to detect when picture is loaded and then change the diplay picture?
I have a code like this:
<img id="image" src="webcam.jpg">
<script>
setInterval(function() {
var myImageElement = document.getElementById('image');
myImageElement.src = 'webcam.jpg?rand=' + Math.random();
}, 1000);
</script>
You should wait for the image to be loaded first, before replacing it.
For this, you can use different approaches. What I usually do, is to create another image which is not visible and replace the one visible once the previous image is loaded.
Your code should look like this if you want to follow this approach:
<img id="image" src="webcam.jpg">
<script>
setInterval(function() {
var url = 'webcam.jpg?rand=' + Math.random();
var img = new Image();
img.src = url;
img.addEventListener('load', function() {
var myImageElement = document.getElementById('image');
myImageElement.src = url;
});
}, 1000);
</script>
What you can also do is play with css styles to make the image hidden or visible depending on the state, but that would make your image appear and disappear which is a bit ugly...
I hope it helps :)
I think you can use something like this:
var _img = document.getElementById('pic'),
urlToImage = 'pic.jpg',
modified = false, lastModified = 0;
setInterval(function(){
fetch(urlToImage)
.then(function(resp){
var f = new File([resp],"file");
switch(true) {
case modified === false:
lastModified = f.lastModified;
modified = true; break;
default:
modified = false;
if(lastModified < f.lastModified) {
modified = true;
}
}
return resp.blob();
})
.then(function(blobdata){
switch(true) {
case modified === true:
var obj_url = URL.createObjectURL(blobdata);
_img.src = obj_url;
break;
}
});
},1000);
<img src="" id="pic" alt="LOCAL pic here"/>
I think that looking at lastModified time in File properties is a good way to assume image was finished written on the server.
Hope this helps.
Try using this after loading the document
$( document ).ready(function() {
setInterval(function() {
var myImageElement = document.getElementById('image');
myImageElement.src = 'webcam.jpg?rand=' + Math.random();
}, 500);
});
Hope this helps

Optimizing performance of a javascript image animation

I've got a question in regards to javascript and dynamically displaying images to
form an animation.
The pictures I have are around 1360x768 in size and quite big despite being .png pics.
I've come up with a code for switching out the pics dynamically, but even run on a local
webserver it is too slow (thus sometimes I see the pic being built).
So my question is: is there a better way to do this than dynamically switching out
the "src" part of the image tag, or is there something else that could be done in combination with that, to make sure that the user doesn't have any strange phenomenons
on the client?
<script>
var title_index = 0;
function display_title()
{
document.getElementById('picture').src=
"pics/title_" + title_index + '.png';
if (title_index < 100) {
title_index = title_index + 5;
setTimeout(display_title,3000);
}
}
</script>
<body onload="setTimeout(display_image,3000)">
<image id="picture" src="pic/title_0.png"/>
</body>
Thanks.
I've had this problem too, even when preloading the images into the cache,
Google's The Hobbit experiment does something interesting. They do low resolution while animating and switch it for a hiresolution if you "pause" (stop scolling in the case of The Hobbit experiment). They also use the HTML5 canvas tag to smooth out the animation.
Here's their blog post about their method:
http://www.html5rocks.com/en/tutorials/casestudies/hobbit-front-end/
Their end product:
http://middle-earth.thehobbit.com
Edit:
Pre loading example:
<!Doctype html>
<head>
<title>test</title>
</head>
<body>
<canvas id="myCanvas" width="1360" height="768"></canvas>
<script type="text/javascript">
var images = {};
var loadedImages = 0;
var numImages = 0;
var context = '';
function loadImages(sources, callback)
{
// get num of sources
for(var src in sources)
{
numImages++;
}
for(var src in sources)
{
images[src] = new Image();
images[src].onload = function()
{
if(++loadedImages >= numImages)
{
callback(images);
}
};
images[src].src = sources[src];
}
}
var canvas = document.getElementById('myCanvas');
context = canvas.getContext('2d');
var sources =
{
frame0: 'http://piggyandmoo.com/0001.png',
frame1: 'http://piggyandmoo.com/0002.png',
frame2: 'http://piggyandmoo.com/0003.png',
frame3: 'http://piggyandmoo.com/0004.png',
frame4: 'http://piggyandmoo.com/0005.png',
frame5: 'http://piggyandmoo.com/0006.png',
frame5: 'http://piggyandmoo.com/0007.png',
frame5: 'http://piggyandmoo.com/0008.png',
frame5: 'http://piggyandmoo.com/0009.png'
};
var width = 1360;
var height = 768;
var inter = '';
var i = 0;
function next_frame()
{
if(numImages > i)
{
context.drawImage(images['frame' + (i++)], 0, 0);
}
else
{
clearInterval(inter);
}
}
loadImages(sources, function(images)
{
//animate using set_timeout or some such...
inter = setInterval(function()
{
next_frame();
}, 1000);
});
</script>
</body>
Code modified from: www.html5canvastutorials.com/tutorials/html5-canvas-image-loader/
You could overcome this issue by preloading the images on page load. This means that the images would then be stored in memory and immediately available to you. Take a look at the following:
JavaScript Preloading Images
http://perishablepress.com/3-ways-preload-images-css-javascript-ajax/

How to contain a mouseover image link without the new image moving objects above it?

What I would like is when the new image loads on mouseover, it does not move any objects above it. I've tried containing it in a div, but for some reason I cannot get this to work. Any help or ideas on what I could do?
Here is a page with what it does now:
click
And here is my code:
<head>
<script type="text/javascript">
function rollover() {
if (!document.getElementById) return
var imgOrSrc;
var imgPreload = new Array();
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
if (images[i].getAttribute('rsrc')) {
imgPreload[i] = new Image();
imgPreload[i].src = images[i].getAttribute('rsrc');
images[i].onmouseover = function() {
imgOrSrc = this.getAttribute('src');
this.setAttribute('src',this.getAttribute('rsrc'))
}
images[i].onmouseout = function() {
this.setAttribute('src',imgOrSrc)
}
}
}
}
</script>
</head>
<body onLoad="rollover()">
<div id="landimage">
<img src="/images/braeden.png" rsrc="/images/braeden2.png" border="0">
</div>
</body>
This is simply because the images are not of the same dimensions. The easiest method would be to increase the canvas size of /images/braeden.png and adding a whitespace to the top of it so it becomes exactly the same height as /images/braeden2.png
If you do not want to to that, then you have to add padding-top to the containing div, when the smaller image is being displayed, to cater for the height difference.

JavaScript - Clicking on an image

I am programming a browser game in JavaScript and need to create a Card Class.
This class has (with other variables) an image, which should be displayed when I create an object. How do I display the object's image and call a function when the image is clicked?
With this code I can display the image wherever I want, but the OnClick function is called instantly when I open the .htm file instead of when I click in the image.
<html>
<head> </head>
<body>
<script type="text/javascript">
function Card(photo){ // this is my object
this.randomVariable=42;
this.pic = new Image(); // creating an Image object inside my Card class.
this.pic.src=photo;
this.pic.height = 300;
this.pic.width = 200;
this.pic.style.position="absolute"; // this 3 lines should set the image's position, and it does.
this.pic.style.top = 50 + "px";
this.pic.style.left = 50 + "px";
this.OnClick = document.write("lala");
}
var myObject = new Card("cardback.jpg");
myObject = document.body.appendChild(coso1.pic); // is this how I should create the image? It appears where I want, but it doesn't seem a "clean" programming.
myObject.OnClick = document.write("lala" + coso1.pic.offsetLeft + coso1.pic.offsetTop); // this is casted when I open the file, and not when I click on the image. *sadface*
</script>
</body>
</html>
Please, some help with detecting when I click on the image and displaying the image in a less dirty way (if it's possible)?
Thanks in advance!
http://jsfiddle.net/CTWWk/1/
var image = new Image();
image.src = 'https://www.google.co.il/images/srpr/logo4w.png';
image.onclick = function(){
alert('I Clicked an image now !');
};
var divy = document.getElementById('divy');
divy.appendChild(image);
Made some changes to your code. Hope it helps!
<html>
<head> </head>
<body>
<script type="text/javascript">
function Card(photo){
var cardInstance = new Image();
cardInstance.src = photo;
cardInstance.addEventListener('click', function (e) {
alert(1);
});
return cardInstance;
}
var myObject = new Card("cardback.jpg");
document.body.appendChild(myObject);
</script>
</body>
</html>

HTML Canvas not displaying image

Im sure this has got to be something simple that I am overlooking, but I can't seem to get my canvas to display an jpg stored on the server.
<img id="test_img" alt="test" src="/media/tmp/a4c1117e-c310-4b39-98cc-43e1feb64216.jpg"/>
<canvas id="user_photo" style="position:relative;"></canvas>
<script type="text/javascript">
var image = new Image();
image.src = "/media/tmp/a4c1117e-c310-4b39-98cc-43e1feb64216.jpg";
var pic = document.getElementById("user_photo");
pic.getContext('2d').drawImage(image, 0, 0);
</script>
the <img> displays as expected, however the canvas is blank, though it does seem to have the correct dimensions. Any one see what I'm doing wrong?
My tired eyes will appreciate any help.
Thanks
you may want to use the following approach
image.onload = function() {
pic.getContext('2d').drawImage(image, 0,0);
}
so you ensure that the image is loaded when trying to draw it.
var initialFloorplanWidth = 0;
var initialFloorplanHeight = 0;
var canvasImage = new Image();
documentReady = function () {
preloadFloorplan();
}
preloadFloorplan = function () {
onLoad = function () {
initialFloorplanHeight = canvasImage.height;
initialFloorplanWidth = canvasImage.width;
var canvasHtml = '<canvas id="MainCanvas" width="' + initialFloorplanWidth + '" height="' + initialFloorplanHeight + '">Canevas non supportés</canvas>';
$("#MainContainer").append(canvasHtml);
var canvas = $("#MainCanvas")[0];
var canvasContext = canvas.getContext("2d");
canvasContext.drawImage(canvasImage, 0, 0);
}
canvasImage.onload = onLoad;
canvasImage.src = initialFloorplan;
}
This code works well.
Try doing that when the document is loaded. I have a feeling your code is running before the image is available. You can also detect when the img itself is loaded. See this.
Maybe it's something to do with the rest of your code. Is "user_photo" identified in the code?

Categories

Resources