rotating images in html - javascript

hello everyone i'm trying to get these images to rotate every 5 seconds in HTML, using javascript. I cant figure out why images are not rotating, if someone could assist me that would be great!! thank you.
<!DOCTYPE html>
<html>
<head>
<title>Concert Ads</title>
<script type="text/javascript">
var image1=new Image()
image1.src="concert1.gif"
var image2=new Image()
image2.src="concert2.gif"
var image3=new Image()
image3.src="concert3.gif"
var image4=new Image()
image4.src="concert4.gif"
var image5=new Image()
image5.src="concert5.gif"
</script>
</head>
<body>
<img src="concert1.gif" name="slide" >
<script type="text/javascript">
var step=1
function slideit() {
document.images.slide.src=eval("image"+step+".src")
if(step<5)
step++
else
step=1
setTimeout("slideit()",5000)
slideit()
</script>
</body>
</html>

<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
var image1 = new Image()
image1.src = "dummyImg1.jpg"
var image2 = new Image()
image2.src = "dummyImg2.jpg"
var image3 = new Image()
image3.src = "dummyImg3.png"
</script>
</head>
<body>
<img src="dummyImg1.jpg" name="slide" >
<script type="text/javascript">
var step = 1
function slideit() {
document.images["slide"].src = eval("image" + step + ".src")
if (step < 3)
step++
else
step = 1
setTimeout("slideit()", 5000)
}
slideit()
</script>
</body>
</html>

Your setTimeout function is incorrect, as you are passing it a string, not a function, and you don't close your function. It is also very inefficient to create a new image item every time; an array will suit you much better. Finally, I think you want to use setInterval not setTimeout.
A working example is here: http://jsfiddle.net/HUP5W/2
Obviously, the images don't work, but, if you look at the console, it is working correctly.
var image = document.getElementById("img1");
var src = ["concert2.gif","concert3.gif","concert4.gif","concert5.gif","concert1.gif"];
var step=0
function slideit() {
image.src = src[step];
image.alt = src[step];
if(step<4) {
step++;
} else {
step=0;
}
}
setInterval(slideit,5000);

Related

how to make javascript validate image before upload image, with prevent the preview image

I have a function to upload an image with FileReader method, if the file image was choose it will showing as a preview image before i upload it, i want to make some validation to read the image width, if it false the preview image should not appear, i'm confused how to make it, since i can not place the file reader inside the image.load scoope: here is my code below :
var input = document.getElementById('fileTrigger');
var el = document.createElement('IMG');
input.addEventListener('change', function({target}){
var file = target.files[0];
var reader = new FileReader();
var image = new Image();
reader.onload = function(e){
if(file) {
image.onload = function(e){
var width = e.target.width;
console.log(width);
if(width !== 100){
console.log('fail')
}
}
image.src = reader.result;
}
el.src = e.target.result;
document.body.appendChild(el)
}
reader.readAsDataURL(file);
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title></title>
</head>
<body>
<input type="file" id="fileTrigger">
</body>
</html>
var input = document.getElementById('fileTrigger');
var el = document.createElement('IMG');
var elResult
input.addEventListener('change', function({target}){
el.src=""
var file = target.files[0];
var reader = new FileReader();
var image = new Image();
reader.onload = function(e){
elResult=e.target.result;
if(file) {
image.onload = function(e){
var width = e.target.width;
console.log(width);
if(width >=300){
console.log('fail')
}else{
el.src = elResult
document.body.appendChild(el)
}
}
image.src = reader.result;
}
}
reader.readAsDataURL(file);
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title></title>
</head>
<body>
<input type="file" id="fileTrigger">
</body>
</html>
Hope this will helps you..:)

html image sldeshow not changing images

ive scripted my self a Image slideshowthere is just the issue that the slideshow stays static on the first Image for each Group.
this Code here is where i have all my Images and then they get selected from it.
< script type = "text/javascript" >
<!-->
var image1 = new Image()
image1.src = "LMH2015_SGVillingen_P1220967.jpg"
var image2 = new Image()
image2.src = "LMH2015_SGVillingen_P1220971.jpg"
var image3 = new Image()
image3.src = "LMH2015_SGVillingen_P1220973.jpg"
var image4 = new Image()
image4.src = "LMH2015_SGVillingen_P1220977.jpg"
var image5 = new Image()
image5.src = "LMH2015_SGVillingen_P1220985.jpg"
//-->
< /script>
and the second part is where the JavaScript should creat the slideshow.
<img src="LMH2015_SGVillingen_P1220967.jpg" width="300" height="300" name="slide" />
<script type="text/javascript">
var step=1
function slideit()
{
document.images.slide.src = eval("image"+step+".src")
if(step<3)
step++
else
step=1
setTimeout("slideit()",3000)
}
slideit()
</script>
<img src="LMH2015_SGVillingen_P1220977.jpg" width="300" height="300" name="slide" />
<script type="text/javascript">
var step=4
function slideit()
{
document.images.slide.src = eval("image"+step+".src")
if(step<5)
step++
else
step=4
setTimeout("slideit()",3000)
}
slideit()
</script>
I hope that there is an easy way of Fixing this Problem and that the way i was having it with the Images still could be left to make it a bit easier is view the Code :D
mark
Try the below function and it is dynamic just call the function with array image and duration.
HTML
<img src="" width="300" height="300" name="slide" />
JS
var imageArr = ["http://stylonica.com/wp-content/uploads/2014/02/Beauty-of-nature-random-4884759-1280-800.jpg", "http://stylonica.com/wp-content/uploads/2014/02/Free-Wallpaper-Nature-Scenes.jpg", "http://www.viralnovelty.net/wp-content/uploads/2014/07/121.jpg"];
function slideShow(imageName, imgArray, duration) {//pass image array and time duration
if(imgArray.constructor !== Array) {
alert("proovide valid image array for slide show");
return false;
}
var step=0;
setInterval(function(){
if(step > imgArray.length - 1){
step = 0; //reset count when the last image
}
document.images[imageName].src = imgArray[step];
step++;
}, duration);
}
slideshow('slide', imageArr, 5000);//call the function with image name
demo link: Slideshow

Cannot see final result of canvas merge with js

I'm merging two images, but result is empty, I've following function:
function merge_avatar_flag(avatar_url,country) {
var flag = new Image('allflags/'+ country.toLowerCase().split(' ').join('_') +'.png');
var avatar = new Image(avatar_url);
var img = new Image();
avatar.onload = function() {
flag.onload = function() {
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
ctx.drawImage(flag, 0, 0);
ctx.drawImage(avatar, 0, 0);
img.src = canvas.toDataURL();
return img;
}
}
}
And the result is merged like this:
$("#changeAvatar").append(merge_avatar_flag(random_avatar,country));
Nothing gets added.
Anything obvious I'm missing here?
You must fully load all images before you try to drawImage them:
After the images are all fully loaded you can combine the images into an img element like this:
$("#combine").click(function(){
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width=imgs[0].width;
canvas.height=imgs[0].height;
ctx.drawImage(imgs[0],0,0); // imgs[0] is the flag
ctx.drawImage(imgs[1],0,0); // imgs[1] is the avatar
$("#changeAvatar").attr("src",canvas.toDataURL());
});
Demo: http://jsfiddle.net/m1erickson/m2DWP/
Code example:
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
#combine{display:none;}
</style>
<script>
$(function(){
var imageURLs=[]; // put the paths to your images here
var imagesOK=0;
var imgs=[];
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stack1/norwayFlag.jpg");
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stack1/avatar.png");
loadAllImages(start);
function loadAllImages(callback){
for (var i=0; i<imageURLs.length; i++) {
var img = new Image();
imgs.push(img);
img.onload = function(){
imagesOK++;
if (imagesOK>=imageURLs.length ) {
callback();
}
};
img.onerror=function(){alert("image load failed");}
img.crossOrigin="anonymous";
img.src = imageURLs[i];
}
}
function start(){
$("#combine").show();
}
$("#combine").click(function(){
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width=imgs[0].width;
canvas.height=imgs[0].height;
ctx.drawImage(imgs[0],0,0);
ctx.drawImage(imgs[1],0,0);
$("#changeAvatar").attr("src",canvas.toDataURL());
});
}); // end $(function(){});
</script>
</head>
<body>
<button id="combine">Combine</button><br>
<img id="changeAvatar">
</body>
</html>

Why I get an Exception 18 when I try to get the image data of an Image with Access-Control-Allow-Origin: * in the response header?

When I try to get the pixels of an image through the method getImageData, I've got this error
"Unable to get image data from canvas because the canvas has been
tainted by cross-origin data. Uncaught Error: SecurityError: DOM
Exception 18"
The image has Access-Control-Allow-Origin: * in the header response. So, I don't understand why I got this error. What I have to do to solve this problem?.
I've tried to add the attribute crossOrigin to the image, but this does not work in Safari.
The code I am working on is below.
<html>
<head>
<title>Example</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
var img = new Image();
img.onload = function() {
var ctx = $('#cnv')[0].getContext('2d');
ctx.drawImage(this, 0, 0);
var originalImageData = ctx.getImageData(0, 0, 300, 300); // Exception 18
};
img.src = 'http://api.thumbr.it/1f86404a001828912f295a74b8a4d337/D-lvXHFIHpY/api.thumbr.it/static/ladies-800.png/400x400c-ebrown-eframe1/thumb.jpg';
$('body').append(img);
</script>
</head>
<body>
<h1>Example</h1>
<img class="image" id="img-rara" src="http://api.thumbr.it/f4414f15f6d6d2639a17c6e1c025d970/D-lvXHFIHpY/api.thumbr.it/static/ladies-800.png/400x400c-ebarcelona-eframe1/thumb.jpg" />
<canvas id="cnv" width="711" height="400" />
</body>
</html>
On the client-side, be sure to set the crossOrigin flag before setting the img.src
img.crossOrigin='anonymous'
Here's your code with crossorigin access set to anonymous:
<html>
<head>
<title>Example</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
var img = new Image();
img.onload = function() {
var ctx = $('#cnv')[0].getContext('2d');
ctx.drawImage(this, 0, 0);
var originalImageData = ctx.getImageData(0, 0, 300, 300); // Exception 18
};
// allow cross-origin access
img.crossOrigin='anonymous'
img.src = 'http://api.thumbr.it/1f86404a001828912f295a74b8a4d337/D-lvXHFIHpY/api.thumbr.it/static/ladies-800.png/400x400c-ebrown-eframe1/thumb.jpg';
$('body').append(img);
</script>
</head>
<body>
<h1>Example</h1>
<img class="image" id="img-rara" src="http://api.thumbr.it/f4414f15f6d6d2639a17c6e1c025d970/D-lvXHFIHpY/api.thumbr.it/static/ladies-800.png/400x400c-ebarcelona-eframe1/thumb.jpg" />
<canvas id="cnv" width="711" height="400" />
</body>
</html>
I have found another way to solve this problem through XMLHttpRequest. This solution is valid for Chrome, Safari, Firefox, and Opera but not in IE. Visit this page http://jsperf.com/encoding-xhr-image-data/12 for more information.
<html>
<head>
<title>Example</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
// See: http://jsperf.com/encoding-xhr-image-data/12
$('body').ready(function(){
data = getImageData(
'http://api.thumbr.it/1f86404a001828912f295a74b8a4d337/D-lvXHFIHpY/api.thumbr.it/static/ladies-800.png/400x400c-ebrown-eframe1/thumb.jpg');
});
function getImageData(url) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, false);
xhr.overrideMimeType('text/plain; charset=x-user-defined');
xhr.send();
var img = $('<img>');
img.attr(
'src',
'data:image/' + getType(xhr.responseText.slice(0, 4)) + ';base64,' + getDataBase64(xhr.responseText)
);
img.load(function() {
var ctx = $('#cnv')[0].getContext('2d');
ctx.drawImage(img[0], 0, 0);
data = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height); // Data!!
});
}
function getDataBase64(data) {
var binary = '';
for (var i = 0; i < data.length; i+=4) {
binary += String.fromCharCode(
data.charCodeAt(i+0) & 0xff,
data.charCodeAt(i+1) & 0xff,
data.charCodeAt(i+2) & 0xff,
data.charCodeAt(i+3) & 0xff
);
}
for (i-=4; i < data.length; i+=1) {
binary += String.fromCharCode(data.charCodeAt(i) & 0xff);
}
return window.btoa(binary);
}
function getType(data) {
if (data.search('PNG') >= 0) {
return 'png';
} else if (data.search('GIF') >= 0) {
return 'gif';
} else {
return 'jpeg';
}
}
</script>
</head>
<body>
<h1>Example</h1>
<img class="image" id="img-rara" src="http://api.thumbr.it/f4414f15f6d6d2639a17c6e1c025d970/D-lvXHFIHpY/api.thumbr.it/static/ladies-800.png/400x400c-ebarcelona-eframe1/thumb.jpg" />
<canvas id="cnv" width="400" height="400" />
</body>
</html>

Rotate random background images with crossfade transition

I have 15 background images in my website. They´re all 1024 x 768 px, and they load random each time the user load the page. Besides that, the images fill the entire screen, no matter what size the browser window is.
I´m stuck with something I want to accomplish, though: I want the images to randomly rotate every n seconds, using a cross fade transition. I´ve reading like a ton of tutorials regarding that subject, but still can´t figure it out.
Thanks in advance, guys!
This is the code:
<head>
<title>Test</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="js/jquery.fullscreenr.js" type="text/javascript"></script>
<script type="text/javascript">
var FullscreenrOptions = {width: 1024, height: 768, bgID: '#bgimg'};
jQuery.fn.fullscreenr(FullscreenrOptions);
var randnum = Math.random();
var inum = 15;
var rand1 = Math.round(randnum * (inum-1)) + 1;
images = new Array
images[1] = "images/contactBG01.jpg"
images[2] = "images/contactBG02.jpg"
images[3] = "images/contactBG03.jpg"
images[4] = "images/contactBG04.jpg"
images[5] = "images/contactBG05.jpg"
images[6] = "images/contactBG06.jpg"
images[7] = "images/contactBG07.jpg"
images[8] = "images/contactBG08.jpg"
images[9] = "images/contactBG09.jpg"
images[10] = "images/contactBG10.jpg"
images[11] = "images/contactBG11.jpg"
images[12] = "images/contactBG12.jpg"
images[13] = "images/contactBG13.jpg"
images[14] = "images/contactBG14.jpg"
images[15] = "images/contactBG15.jpg"
onload=function(){
document.getElementById("bgimg").src=images[rand1];
}
</script>
</head>
<body>
<img id="bgimg" src="" />
<div id="realBody">
<img id="exampleDiv" src="images/contact_top.png"/><br>
<img id="exampleDivBottom" src="images/contact_pie.gif">
</div>
</body>
</html>
if jQuery is an option:
// Wait for DOM-ready, don't use `window.onload`
$(function() {
// The image we are going to be updating
var img = $("#bgimg"),
// The number of seconds between transitions
every = 15 * 1000,
// The speed at which to fade, can be: 'slow',
// 'medium, 'fast', or a number (in milliseconds)
fadeSpeed = "slow",
// The images to cycle through
imgs = [
"images/contactBG01.jpg",
"images/contactBG02.jpg",
"images/contactBG03.jpg",
"images/contactBG04.jpg",
"images/contactBG05.jpg",
"images/contactBG06.jpg",
"images/contactBG07.jpg",
"images/contactBG08.jpg",
"images/contactBG09.jpg",
"images/contactBG10.jpg",
"images/contactBG11.jpg",
"images/contactBG12.jpg",
"images/contactBG13.jpg",
"images/contactBG14.jpg",
"images/contactBG15.jpg"
];
// Use setTimeout to schedule the image to be updated
// periodically
setTimeout(function() {
// Fade the image out, then when done...
img.fadeOut( fadeSpeed, function() {
// Use the length of the array to generate a number
var newSrc = imgs[Math.round(Math.random * (imgs.length-1)) + 1];
// Replace the src, then fade back in
img
.attr("src", newSrc )
.fadeIn( fadeSpeed )
}, every );
});
hope that helps! cheers.

Categories

Resources