Why won't image auto refresh - javascript

Trying to get images to refresh themselves with javascript a set number of times, then stop (to avoid large cache generation). This code won't function though, so not sure what's missing?
<script>
var c = 0;
function fnSetTimer()
{
document.getElementById('refreshimage1').src='http://68.116.42.142:8080/cam_4.jpg?\'+new Date().getMilliseconds();
var t = setTimeout(fnSetTimer,5000);
c=c+1;
if(c>5)
clearTimeout(t);
}
</script>
<img src="http://68.116.42.142:8080/cam_4.jpg"; id="refreshimage1" onload="fnSetTimer()" width="400" />
However, this code does work:
<img src="http://68.116.42.142:8080/cam_4.jpg"; id="refreshimage2" onload="setTimeout('document.getElementById(\'refreshimage2\').src=\'http://68.116.42.142:8080/cam_4.jpg?\'+new Date().getMilliseconds()', 5000)" width="400" />
So if you place both side by side, the bottom image will refresh (indefinitely), but the top image just loads once and never refreshes. Any thoughts what I missed in the top code?

The problem is that the function re-loads the image, which calls the function, which re-loads the image...
You also had a problem with the image url - '\' is used to escape special characters, if you want a slash you need two - '\\'
PUT THIS IN YOUR HEADER
<script language="javascript">
function fnSetTimer(image, src, counter, limit)
{
image.onload = null;
if(counter < limit)
{
counter++;
setTimeout(function(){ fnSetTimer(image, src, counter, limit); },5000);
image.src= src+ '?\\'+new Date().getMilliseconds();
alert(counter); // show frame number
}
}
</script>
PUT THIS IN THE BODY
<img src="http://68.116.42.142:8080/cam_4.jpg"; id="refreshimage1" onload="fnSetTimer(this, this.src, 0, 5);" width="400" />
This should fix it for you - it only fires onLoad once and then loops through 5 times, and you should be able to edit the image tag in Wordpress, etc.
MAKE SURE YOU GIVE EACH IMAGE A DIFFERENT ID

Related

Wait for image to load plugin not functioning

I'm using the plugin from https://github.com/alexanderdickson/waitForImages to detect when is the image loaded.
Below is my code:
$('.marquee').waitForImages(function() {
console.log('All images have loaded.');
setTimeout(startMarquee);
}, function(loaded, count, success) {
console.log(loaded + ' of ' + count +
' images has ' + (success ? 'loaded' : 'failed to load') + '.');
$(this).addClass('loaded');
});
I will start a marquee scrolling of images when the images is loaded complete.
My problem is, some images had not yet load but just show a small empty square box like this:
,
the plugin also consider it already load. Any idea how to fix it?
Does showing a small empty square box only is consider image loaded?
Just write your own.
<marquee id="marquee" style="visiblity:hidden">
<img src="image1.jpg" onload="countMe(this,1)" onerror="countMe(this,0)"/>
<img src="image1.jpg" onload="countMe(this,1)" onerror="countMe(this,0)"/>
<img src="image1.jpg" onload="countMe(this,1)" onerror="countMe(this,0)"/>
</marquee>
<script>
var imageCount = 0, nofImages=$("#marquee img");
function countMe(img,success) {
if (!success) $(img).hide();
imageCount++;
if (imageCount == nofImages) $("#marquee").show();
}
</script>
If you want to give the image a chance and not load the marquee if permanent error you can try
<marquee id="marquee" style="visiblity:hidden">
<img src="image1.jpg" onload="countMe(this)" onerror="reloadMe(this)"/>
<img src="image2.jpg" onload="countMe(this)" onerror="reloadMe(this)"/>
<img src="image3.jpg" onload="countMe(this)" onerror="reloadMe(this)"/>
</marquee>
<script>
var imageCount = 0, nofImages=$("#marquee img");
function countMe(img) {
imageCount++;
if (imageCount == nofImages) $("#marquee").show();
}
function reloadMe(img) {
var tries = img.getAttribute("tries")?parseInt(img.getAttribute("tries"),10):1;
if (tries) == 3) return; // stop it
tries++;
img.setAttribute("tries",tries);
img.src=img.src;
}
</script>
If you want to wait till all page images loaded before running your marquee code you can use:
$(window).on("load", function() {
// all page html and images loaded
});
More details can be found in this questions:
Official way to ask jQuery wait for all images to load before executing something

onload triggering too early for ajax content in IE

I have a page where the images are supplied dynamically and are scaled with javascript to fit within the appropriate dimensions. This was initially being done with an onload attribute in the img tag, but then I noticed that in IE, the height being returned for the image was much less in some cases than the actual height, which ended up distorting the image. I solved this by finding and resizing all the images after $(window).load() was done, which worked fine for the initial page load, but I also have the page set up to add more content with an ajax call. For the ajax content, I tried some code I found on here that improved the problem, but didn't completely solve it. Here is an example of one of my image tags
<img id="img<?php echo $prodModObj->rolloverID; ?>" class="mbImg unsized" src="<?php echo $prodModObj->img; ?>" alt="<?php echo $prodModObj->name; ?>" onerror="swapImage(<?php echo $prodModObj->rolloverID; ?>)" />
The swapImage function just swaps out the image with a placeholder if there is an error while loading. Here is my JS
function swapImage(thisImgID) {
var imgID = 'img#img' + thisImgID;
$(imgID).attr('src', '/images/NoImageAvail.jpg');
}
function checkImage(thisImgID, fitDimension, spaceDimension) {
var imgID = 'img#img' + thisImgID;
var imgHeight = $(imgID).height();
var imgWidth = $(imgID).width();
var displayHeight, displayWidth, newMargin;
if (imgHeight > imgWidth) {
displayHeight = fitDimension;
displayWidth = imgWidth*(displayHeight/imgHeight);
} else if (imgHeight < imgWidth) {
displayWidth = fitDimension;
displayHeight = imgHeight*(displayWidth/imgWidth);
} else {
displayWidth = fitDimension;
displayHeight = fitDimension;
}
$(imgID).css('height', displayHeight);
$(imgID).css('width', displayWidth);
newMargin = ((spaceDimension - displayHeight)/2);
$(imgID).css('margin-top', newMargin);
$(imgID).removeClass('mbImg unsized').addClass('mbImg sized');
}
And then on the page I have
$(window).load(function(){
// Resize product images
$('.mbImg.unsized').each( function() {
var rolloverID = $(this).attr('id').substr(3);
checkImage(rolloverID,250,270);
});
});
And then in the success portion of the ajax call, I have
$('.mbImg.unsized').each( function() {
var rolloverID = $(this).attr('id').substr(3);
if (this.complete) {
checkImage(rolloverID,250,270);
} else {
$(this).on('load', function(){
checkImage(rolloverID,250,270);
});
}
});
Images that have been cached by the browser work fine, and the images in the initial page load work fine, but about 1 in 5 of new ajax images come out distorted. Is there another method I can use to size all the ajax images correctly in IE?
Thanks for your help,
Maybe come at it another way?
I've tried to move away from html4 style tag syntax, to using simple html5 tags and a combination of JavaScript and CSS to control the "view".
Check out this fiddle:
http://jsfiddle.net/zacwolf/s1haq3mz/
A question becomes how you want your images to flow, as using this approach all of the images are technically the same size (as demonstrated by the border). Also note that the .src for the second image I tweeked the url a bit so that it was a 404 for the image file, which triggered the one error image instead.
<img id="one" class="myclass" />
<img id="two" class="myclass" />
<style>
.myclass{
height:270px;
width:250px;
background-position:center,center;
background-repeat:no-repeat;
background-size:contain;
}
</style>
<script>
var one = new Image();
one.onerror=
function(){
this.src='http://leomarketingep.com/wp-content/uploads/Sign-Error-icon.png'
}
one.onload=
function(){
$('#one').css('background-image','url('+one.src+')')
}
one.src='https://cjjulian.files.wordpress.com/2009/04/blah_blah_blah-703369.jpg';
var two = new Image();
two.onerror=
function(){
this.src='http://leomarketingep.com/wp-content/uploads/Sign-Error-icon.png';
}
two.onload=
function(){
$('#two').css('background-image','url('+two.src+')')
}
two.src='https://cjjulian.files.wordpress.com/2019/04/blah_blah_blah-703369.jpg';
</script>
If you have a lot of images, you can populate an array of Image objects, for better referencing, etc.

How to slow down an image slideshow in html?

Looking for a (simple) way to create a slideshow for my website I found the following question here: How to create image slideshow in html?. I borrowed the (corrected) code, adapted it to my needs and now I have what I wanted, but the transition between the images is too fast. It's not about the speed of the slideshow, but the blending or fading from one image into the next. The changes come too suddenly. I want them to happen gradually and smoothly. What can I add to it or how can I change it to slow it down? Here is it:
<head>
<script type="text/javascript">
var image1 = new Image()
image1.src = "images/pentagg.jpg"
var image2 = new Image()
image2.src = "images/promo.jpg"
</script>
</head>
<body>
<p><img src="images/pentagg.jpg" width="500" height="300" name="slide" /></p>
<script type="text/javascript">
var step=1;
function slideit()
{
document.images.slide.src = eval("image"+step+".src");
if(step<2)
step++;
else
step=1;
setTimeout("slideit()",2500);
}
slideit();
</script>
</body>
Thank you for your help.
You can do it by doing following change in your code
setTimeout(slideit(),10000);
instead of
setTimeout(slideit(),2500);
Here 2500 means 2.5 seconds and 10000 means 10 seconds, according to need you can use any parameter.
Hope this can solve your problem.
As per your comment, you want to show the transition between image changes, then use jquery and do this in sequence:
Animate opacity to 0 (fadeOut),
change the image,
animate the opacity to 1 (fadeIn)
or write your own animation logic to do the same without jquery.
Solution using jquery:
var $slide = $(document.images.slide);
function slideit() {
//fadeout the last image.
$slide.fadeOut(function () {
document.images.slide.src = eval("image" + step + ".src");
//after changing the image, fadeIn the new image.
$slide.fadeIn(function () {
if (step < 2) step++;
else step = 1;
//everything is done... now run the timer for next slide.
setTimeout(slideit, 5500);
});
})
}
jsfiddle: http://jsfiddle.net/vaf84vLd/

Image.complete is true after onload, but after onload second image not anymore

I'm using Javascript to load 2 images and drawing them on a canvas.
I use the onload event of an image to drawn the images after they are both loaded.
var loadedImagesCount = 0;
var NUM_OF_TILES=2;
window.onload=function(){
background.onload = imageOnLoad();
background.src ="background.png";
layer1 = document.getElementById("layer1");
ctx1 = layer1.getContext("2d");
character.onload = imageOnLoad();
character.src ="character.png";
layer2 = document.getElementById("layer2");
ctx2 = layer2.getContext("2d");
}
function imageOnLoad(){
loadedImagesCount++;
window.alert(''+loadedImagesCount+ ' ' + background.complete + ' ' + character.complete);
if (loadedImagesCount==NUM_OF_TILES) drawAll();
}
The imageOnLoad() is called twice (as expected). The first time is says (through an alert) that both images are loaded. The second time it says that the character image is loaded, but the background image not anymore? How is this possible? Why would it unload the image again? After a refresh this does not happen anymore, it only happens the first time you load the page.
And because the background is not loaded, when the canvas is drawn, only the character is being drawn.
This maybe because you have not declared background as a global variable outside of the window.onload function. So background is not the variable you think it is.
Check this code that works as expected and is derived from yours and notice how background and characters are "vared" outside of the window.onload function :
<html>
<script language="javascript">
var loadedImagesCount = 0;
var NUM_OF_TILES=2;
var background;
var character;
window.onload=function(){
background = document.getElementById("background");
character = document.getElementById("character");
background.onload = imageOnLoad();
background.src ="HSHOP.jpg";
character.onload = imageOnLoad();
character.src ="HSHOP 2.jpg";
}
function imageOnLoad(){
loadedImagesCount++;
window.alert(''+loadedImagesCount+ ' ' + background.completes + ' ' + character.complete);
//if (loadedImagesCount==NUM_OF_TILES) drawAll();
}
</script>
<body>
<img id="background"/>
<img id="character"/>
</body>
</html>
Quick note : As a general rule try to clean up your code as much as possible before posting it so that it is easier for us to find what's going wrong.
Problem solved. The onload variable needs a method without the parentheses, if you use the parentheses it will call the method immediately.

Save canvas to image via toDataURL failed

I create a test code below and you can manipulate it on Jsfiddle:
http://jsfiddle.net/Stallman41/57hvX/31/
HTML:
<canvas id="test_canvas" style="background-color : #FFFF00" ; width="500px"
; height="340px"></canvas>
<br>
<button id="test_put_btn">Put an image</button>
<br>
<button id="save_dataURL">Save to dataURL</button>
<br>
<button id="draw_back">Final step: draw 3 images back.</button>
<br>
<img id="first_img"; width="100px" ; height="100px" ;></img>
<img id="second_img"; width="100px" ; height="100px" ></img>
<img id="third_img"; width="100px" ; height="100px" ;></img>
Javascript:
var drawing_plate;
var context;
var dataURL_arr = new Array();
$(document).ready(function () {
drawing_plate = document.getElementById("test_canvas");
context = drawing_plate.getContext('2d');
$("#test_canvas").bind("mousedown", Touch_Start);
$("#test_canvas").bind("mousemove", Touch_Move);
$("#test_canvas").bind("mouseup", Touch_End);
}); //document ready.
function Touch_Start(event) {
event.preventDefault();
touch = event;
touch_x = touch.pageX;
touch_y = touch.pageY;
line_start_x = touch.pageX - 0;
line_start_y = touch.pageY - 0;
context.beginPath();
context.moveTo(line_start_x, line_start_y);
}
function Touch_Move(event) {
event.preventDefault();
touch = event; //mouse
line_end_x = touch.pageX - 0;
line_end_y = touch.pageY - 0;
context.lineTo(line_end_x, line_end_y);
context.stroke();
}
$("#test_put_btn").click(function () {
var test_img = new Image();
test_img.src = "http://careerscdn.sstatic.net/careers/gethired/img/careers2- ad-header-so-crop.png";
context.drawImage(test_img, 0, 0);
});
$("#save_dataURL").click(function () {
dataURL_arr.push(drawing_plate.toDataURL("image/png"));
});
$("#draw_back").click(function () {
var f_image= $("#first_img")[0];
var s_image= $("#second_img")[0];
var t_image= $("#third_img")[0];
f_image.onload= function()
{
f_image.src= dataURL_arr[0];
}
f_image.src= dataURL_arr[0];
s_image.onload= function()
{
s_image.src= dataURL_arr[0];
}
s_image.src= dataURL_arr[0];
t_image.onload= function()
{
t_image.src= dataURL_arr[0];
}
t_image.src= dataURL_arr[0];
});
I develop a drawing plate on Android system, saving the drawings to a dataURL string. They can draw something on the canvas and put images on the canvas. And I need to let the users see their drawings on small icons.
I use canvas.toDataURL("image/png") to save the base64 string. And I choose <img> as the small icon container. However, what I got is only the drawings can be shown on the icon, and usually, when I write img.src= canvas.toDataURL("image/png"); the image shows nothing!
I investigate the issue for long time.
1. I think the problem might be the dataURL string is too long?
2. The support of the OS: Android?
The code in Jsfiddle here shows a similar procedure on my Android PhoneGap development.
First , you just draw something on the canvas, and press Press an image, and then Save to dataURL. But you should do the process three times. In this condition, the string array contains the base64 string generated by the drawings and the image.
In the final, you press Final step: draw 3 images back., nothing will be shown on the image icon.
In conclusion:
In my experience, as I write img.src= canvas.toDataURL("image/png"); (no matter the img is an dom element or var img = new Image();). It can't always work: sometimes it works... but sometimes not...(I work on Android 4.0.1, phonegap 1.7.0)
Second, especially if I store lots of base64 strings to an array, assigning them to lots of image DOM element, it definitely fails.
Third, if the user only draw something on the canvas, it can always work.( Except the example code in the Jsfiddle, but it works on my Android system...)
But if he draw an image context.drawImage(~) the image wouldn't show the pic.
Too much confusions...
I need to let the user can view their drawings in small icon, any alternative?
Some References:
1
2
3
I just stumbled across this question.
Click Put an image, then click Save to dataURL, then check your JavaScript console for something like:
SecurityError: DOM Exception 18
It's a browser security feature. Because you've inserted an image from a different domain, it counts as a cross-origin request.
If you eliminate the security error, you can export the canvas to a data URL.
Another thing in your code.
The image you try to draw onto the canvas into your test_put_btn onclick event handler, your image will never show up (or it will sometimes work accidentally) because you don't wait for your image to be loaded to draw it onto the canvas.
You have to handle the "onload" event of your image and draw it into the handler to permit the drawing of your image.
Before your test_img.src statement, you have to put :
test_img.onload = function()
{
context.drawImage(test_img, 0, 0);
};
Plus, the image you try to access is not accessible --> For me it does not work

Categories

Resources