This question already has an answer here:
How to change the css attribute of #header using jQuery and an array of images?
(1 answer)
Closed 8 years ago.
As you can see in my fiddle here, http://jsfiddle.net/HsKpq/460/ I am trying to show the images into the
$('#header').css('background-image',..................).fadeTo('slow',1);
How can I do this?
var img = 0;
var imgs = [
'http://www.istockphoto.com/file_thumbview_approve/9958532/2/istockphoto_9958532-sun-and-clouds.jpg',
'http://www.istockphoto.com/file_thumbview_approve/4629609/2/istockphoto_4629609-green-field.jpg',
'http://www.istockphoto.com/file_thumbview_approve/9712604/2/istockphoto_9712604-spring-sunset.jpg'
];
// preload images
$.each(imgs,function(i,e){var i=new Image();i.src=e;});
// populate the image with first entry
$('img').attr('src',imgs[0]);
var opacity = 0.1; // change this for minimum opacity
function changeBg() {
$('img').fadeTo('slow',opacity,function(){
$('#header').css('background-image',..................).fadeTo('slow',1);
});
}
setInterval(changeBg,5000);
You can do it without img elements, using backgound css property, like here:
var img = 0;
var imgs = [
'http://www.istockphoto.com/file_thumbview_approve/9958532/2/istockphoto_9958532-sun-and-clouds.jpg',
'http://www.istockphoto.com/file_thumbview_approve/4629609/2/istockphoto_4629609-green-field.jpg',
'http://www.istockphoto.com/file_thumbview_approve/9712604/2/istockphoto_9712604-spring-sunset.jpg'
];
// preload images
$.each(imgs,function(i,e){var i=new Image();i.src=e;});
var img = imgs[0];
var opacity = 0.1; // change this for minimum opacity
function changeBg() {
$('#header').fadeTo('slow',opacity,function(){
$('#header').css('background-image', 'url(' + img + ')').fadeTo('slow',1);
});
}
setInterval(changeBg,5000);
Don't know what you were trying to do with the background image and then populating the first image to a non-existent element.
Here is an updated fiddle: http://jsfiddle.net/HsKpq/464/
But this may be what you are looking for to show the images :
var $h_image = $('#headerImage');
function changeBg() {
$h_image.fadeTo('slow',opacity,function(){
$h_image.attr('src', imgs[Math.floor((Math.random() * 3))]).fadeTo('slow',1);
});
}
You also need to change your HTML to this :
<div id="header"><img id="headerImage"/></div>
Related
I am working in a project where I need to generate a profile picture of any member and its reviews, and some data, I started working with GDI, but it was so hard to understand, so I searched for other options and found Html2Canvas that works with javascript/jquery, everything is fine, the only thing I couldn't handle, and would like to know if there is a way to hide the source html div without breaking the result image.
Ex:
This is how is it now
This is how it should look
So, when I apply display:none on the css of the source div, the image result is like this:
And finally here is the code that I have so far
var div_to_hide = $("#mydiv:hidden");
$(function() {
$('span.stars').stars();
});
html2canvas([document.getElementById('mydiv')], {
onrendered: function (canvas) {
document.getElementById('canvas').appendChild(canvas);
var data = canvas.toDataURL('image/png');
var image = new Image();
image.src = data;
document.getElementById('image').appendChild(image);
}
});
$.fn.stars = function() {
return $(this).each(function() {
var val = parseFloat($(this).html());
val = Math.round(val * 4) / 4;
var size = Math.max(0, (Math.min(5, val))) * 16;
var $span = $('<span />').width(size);
$(this).html($span);
});
}
https://jsfiddle.net/ricardojriosr/6ap9Lx1f/8/
Now the question is how do I made this work showing only the image and not the HTML source. Thanks in advace.
Instead of trying to hide it before, hide (or remove) it after the canvas is rendered.
I'm not sure why var div_to_hide equals $("#mydiv:hidden"); but if you change it to var div_to_hide = $("#mydiv"); then, on line 12, after appending the image, you can run div_to_hide.hide();
And to avoid a flash of the HTML content, you can use some CSS trickery to cover up the original HTML. I made an example here, but you can adjust to fit whatever your actual needs are. https://jsfiddle.net/m5zq2kzn/
I had the same issue.
The solution that worked for me is a css trickery to position the div that I want to hide offscreen:
.offscreen {
position:absolute;
left:-10000px;
top:auto;
width:1px;
height:1px;
overflow:hidden;
}
Then use it like this:
html2canvas(document.getElementById("ticket_template"))
.then((canvas) => {
let imgData = canvas.toDataURL('image/png');
});
I'm making an image carousel i'm bounded to use background-image property instead of using
<img src="Image">
tag. my carousel is working if I use img tag . But its not working when I use background-image property, how can I modify my code with background-image property.
see my fiddle :https://jsfiddle.net/korLasen/ and update it please thanks :)
or you can see code here
(function(){
var image = $('#imageSlider');
var imageSet = ['http://www.exposureguide.com/images/top-ten-tips/top-ten-photography-tips-1e.jpg','http://images.clipartpanda.com/cliparts-images-aTqyrB8TM.png'];
var index = 0;
function imageSliderSet(){
image.setAttribute('data-background', imageSet[index]);
index++;
if(index >= imageSet.length){
index = 0;
}
}
setInterval = (imageSliderSet, 2000);
})();
This is quite a strange question... however, I am not one to judge :)
Here is a jsfiddle based on your example. I ended up using jquery for this. I hope this is somewhere near what you were looking for!
This is based on changing every two seconds. To extend that, you can change line 18 in the jquery. Here is the jquery:
$( document ).ready(function(){
var image = $('#imageSlider');
var imageSet = ['http://www.exposureguide.com/images/top-ten-tips/top-ten-photography-tips-1e.jpg','http://images.clipartpanda.com/cliparts-images-aTqyrB8TM.png'];
var index = 0;
window.setInterval(function(){
image.css('background-image', "url('" + imageSet[index] + "')");
index++;
if(index >= imageSet.length){
index = 0;
}
//here you can adjust the time interval for each photo
}, 2000);
});
I have a PSD file with a bunch of layers that are frames for an animation. How can I create an animation from this using JQuery/JavaScript?
Will I have to save each layer as a separate image, is there a way to have the one image with multiple layers animated? To clarify, I don't want the actual image to move, I just want different layers to be displayed as if they were frames of an animation. What's the standard way this is done with JavaScript?
Thanks!
Here is a fiddle that demonstrates the javascript timer + individual images approach.
Fiddle: http://jsfiddle.net/ZVFu8/2/
The basic idea is to create an array with the names of your images.
var img_name_arr = [];
var img_name_root = "anim-";
var img_name_ext = ".gif";
var num_images = 12;
// init arr of img names assuming frames are named [root]+i+[extension]
for (i = 0; i<=num_images; i++) {
img_name_arr.push(img_name_root + i + img_name_ext);
}
For the animation, use setInterval(). In javascript, an interval executes periodically. You specify the code to execute and the interval at which the code should be run (in milliseconds).
Every time your interval is called, you can display a new image by setting the "src" attribute of the image tag to the next index in the image_name array.
// Create an interval, and save a handle to the interval so it can be stopped later
anim_interval = setInterval(function() {
$("#player").attr("src", s + img_name_arr[(anim_frame++ % num_images)+1] );
}, frame_interval);
Depending on how long your animation is and how large each image file is, it might be necessary to optimize this by pre-loading these images. Before the animation starts, you could create an img tag for each image and hide it. Then, instead of altering the "src" attribute to change the image, you would actually hide the current image and un-hide the next image in the previous image's place.
Here is the full code if you wish to run this locally:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<a id="anim_control" href="">Start</a>
<img id="player" src="" />
<script>
var s = "http://" + atob("YmVucmlkb3V0LmNvbQ==") + "/";
var img_name_arr = [];
var img_name_root = "anim-";
var img_name_ext = ".gif";
var num_images = 12;
var framerate = 1; // Desired frames per second
var frame_interval = 1000/framerate;
$(function(){
// Document is ready
// init arr of img names
for (i = 0; i <= num_images; i++) {
img_name_arr.push(img_name_root + i + img_name_ext);
}
var anim_interval = null;
var playing = false;
var anim_frame = 0;
// Define an interval that will execute every [frame_interval] milliseconds
$("#anim_control").on("click", function(e) {
e.preventDefault();
if (playing == true) {
playing = false;
$(this).html("Start");
clearInterval(anim_interval);
} else {
playing = true;
$(this).html("Stop");
anim_interval = setInterval(function() {
//console.log(s + img_name_arr[(anim_frame++ % num_images)+1]);
$("#player").attr("src", s + img_name_arr[(anim_frame++ % num_images)+1] );
}, frame_interval);
}
});
});
</script>
<style>
#player {
width: 320px;
height: 240px;
border: 1px solid #000;
}
</style>
I'm trying to make some JavaScript code to change the background of two div tags every X seconds. Here is my code:
HTML
<div id="bg_left"></div>
<div id="bg_right"></div>
CSS
body{
height:100%;
}
#bg_left{
height:100%;
width:50%;
left:0;
position:fixed;
background-position:left;
}
#bg_right{
height:100%;
width:50%;
right:0;
position:fixed;
background-image:url(http://presotto.daterrawebdev.com/d/img/pp_hey_you_bg.png);
background-position:right;
}
JAVA SCRIPT
function carousel_bg(id) {
var bgimgs = [ 'pp_hey_you_bg.png', 'burningman_bg.png' ];
var img1 = bgimgs[id];
var img2 = bgimgs[id+1];
var cnt = 2;
$('#bg_left').css("background-image", "url(http://presotto.daterrawebdev.com/d/img/"+img1+")");
$('#bg_right').css("background-image", "url(http://presotto.daterrawebdev.com/d/img/"+img2+")");
id = id + 1;
if (id==cnt) id = 0;
setTimeout("carousel_bg("+id+")", 10000);
}
$(document).ready(function() {
carousel_bg(0);
});
The background-images should be changing randomly, but they don't even change at all.
OK, I see the issue in your jsFiddle. Because you're passing a string to setTimeout() that string will be evaluated only at the top level scope. But, the function name you were passing is not at the top level scope (it's in an onload handler for the jsFiddle). So, I changed the way your JS is positioned in the jsFiddle so it is now at the top level scope. I also fixed up the logic for selecting an image and it now works here: http://jsfiddle.net/jfriend00/awVYP/
And, here's a cleaned up version that does not pass a string to setTimeout() (a much better way to write javascript) that passes a local function and uses a closure to keep track of the current index: http://jsfiddle.net/jfriend00/LVGNN/
function carousel_bg(id) {
var bgimgs = [ 'pp_hey_you_bg.png', 'burningman_bg.png' ]; // add images here..
function next() {
if (id >= bgimgs.length) {
id = 0;
}
var img1 = bgimgs[id];
id++;
if (id >= bgimgs.length){
id = 0;
}
var img2 = bgimgs[id];
$('#bg_left').css("background-image", "url(http://presotto.daterrawebdev.com/d/img/"+img1+")");
$('#bg_right').css("background-image", "url(http://presotto.daterrawebdev.com/d/img/"+img2+")");
setTimeout(next, 1000);
}
next();
}
$(document).ready(function() {
carousel_bg(0);
});
Previous comments on earlier version so of the OP's code:
$('#body')
should be:
$('body')
or even faster:
$(document.body)
Also, your jsFiddle shows a bit of an odd issue. Your CSS has a background image on the HTML tag, but your javascript sets a semi-transparent background image on the body tag. Is that really what you want?
For testing I added another image to the array so that we got some distinction in the sorting.
function carousel_bg(id) {
var bgimgs = [ 'http://presotto.daterrawebdev.com/d/img/pp_hey_you_bg.png', 'http://presotto.daterrawebdev.com/d/img/burningman_bg.png', 'http://gallery.orobouros.net/var/albums/2012/NewYorkComicCon2012/Legend-of-Korra/nycc_20121013_164625_0041.jpg?m=1354760251' ]; // add images here..
var img1 = bgimgs[id+1];
var img2 = bgimgs[id];
var cnt = bgimgs.length; // change this number when adding images..
$('#bg_left').css("background-image", "url("+img1+")");
$('#bg_right').css("background-image", "url("+img2+")");
id = id + 1;
if (id== (cnt - 1) ) id = 0;
setTimeout("carousel_bg("+id+")", 10000);
}
Two changes here:
For your total image count, I am retrieving the total count of images in the array dynamically instead of by hand (bgimgs.length)
In your conditional to reset the id value, subtract the total count by 1. Since JS has zero-based indexes, not doing this will get you an undefined error (a 3 item array will spit out a value of 4 in your original code on the last iteration).
While this code does loop through your array, it's not random. That's another topic.
For those not using JQuery, simply do the following:
document.body.style.backgroundImage="url(images/mybackgroundimage.jpg)";
This question already has answers here:
How to add a list of images to the document from an array of URLs?
(2 answers)
Closed 7 years ago.
needing some help. I have two divs that I need to fill with images. The images can't be random as div 1's image needs to correspond to div 2's. I've been playing around and have managed to get the javascript working to this point. The problem is I need the script to write to the div backgrounds rather than fill the div with an image.
<script>
var random = Math.random();
function random_imglink(arr){
var ry = Math.floor(random*arr.length);
document.write(
'<img src="'+arr[ry]+'" border=0 class="two">'
);
}
var myimages = [
"img1.jpg", "img2.jpg","img3.jpg"
],
myimagesA = [
"img1b.jpg","img2b.jpg","img3b.jpg"];
</script>
<div><script>random_imglink(myimages);</script> </div>
<DIV><script>random_imglink(myimagesA);</script></div>
Your code needed quite an overhaul. This is what it should look like after being fixed:
<div id='a'>A</div>
<div id='b'>B</div>
<script>
var random = Math.random();
function random_imglink(arr, id){
var ry = Math.floor(random*arr.length);
document.getElementById(id).style.backgroundImage = "url('" + arr[ry] + "')";
}
var myimages = [
"http://img1.jpg.to"],
myimagesA = ["http://img1b.jpg.to"];
random_imglink(myimages, 'a');
random_imglink(myimages, 'b');
</script>
Demo
To set an image as the background of an element you can use this:
document.getElementById("myDivId").style.backgroundImage = "url(/path/to/img)";
In your code, you could do it something like:
var random = Math.random();
function random_imglink(divId, arr){
var ry = Math.floor(random*arr.length);
document.getElementById(divId).style.backgroundImage = "url(" + arr[ry] + ")";
}
var myimages = ["img1.jpg", "img2.jpg","img3.jpg"],
myimagesA = ["img1b.jpg","img2b.jpg","img3b.jpg"];
random_imglink("firstDiv", myimages);
random_imglink("secondDiv", myimagesA);
html:
<div id="firstDiv"></div>
<div id="secondDiv"></div>
Smallest possible change of the current code; make the function write a div tag with a style attribute instead of an image tag:
document.write('<div style="background:url('+arr[ry]+')">');
Put the script where you want the start tag:
<script>random_imglink(myimages);</script> </div>