I have many div elements that I pull and each of them have a background-image. Some elements however represent a gif and when I mouse hover over them I wish to play the gif and have it stop or reset when the mouse exit.
I see many examples of gif animation with an image tag but I cannot seem to get it to work with a background-image.
So for each Image I have the starting image for the gif as well as the .gif extension to the full content.
I am reading this question here for reference: Start GIF On Mouse Hover and Pause Otherwise?
which brings me to my question: what is a gif?
Is it a collection of smaller images for the "animation"? I see alot of "image slicing" terminology or having multiple images that cycle through to simulate the animation. But is it possible to show a gif through html/css/js with just the starting image and the .gif url?
$container.on('mouseenter', ".gif", function (event) {
var target = event.target;
var $target = $(target);
//play gif
$target.css("background-image", "url(" + theGIFurl + ")");
});
.item gif{
background-image: url(theJPGurl); /
}
A gif is a type of bitmap image. It used to be very popular, because it can have transparent pixels (in contrast to jpg). But in that regard it is replaced by png, which is generally smaller, supports alpha transparency (where gif pixels are either fully transparent or fully opaque), and most importantly, gif images are limited to 256 colors.
One other feat of gif images is their animation. You may know them from old websites that show a rotating envelope or something.
An animated gif image is just a collection of images combined in a single file. Such a file also contains additional timing information in the file. However, a gif image is not a smart object that can be controlled. You can't start, stop, pause or speed up a gif image using JavaScript. It just contains frames and can be looped or not, but all that information is in the file.
So, while you can animate using JavaScript or CSS by showing different images, this is a different technique than just showing an animated gif.
So, maybe it's best to investigate other techniques. While gifs are basically very simple, they are also very limited in their use. For instance, you can't reliably time a script to run the end of a gif animation.
-edit-
Apparently you can (in FireFox) pause a gif file.
$container.on('mouseenter', ".gif", function (event) {
var target = event.target;
var $target = $(target);
//play gif
$target.css("background-image", "url(" + theGIFurl + ")");
});
.item gif{
background-image: url(theJPGurl); /
}
$container.on('mouseenter', ".gif", function (event) {
var target = event.target;
var $target = $(target);
//play gif
$target.css("background-image", "url(" + theGIFurl + ")");
});
.item gif{
background-image: url(theJPGurl); /
}
If anyone could comment, I did find this example which solves this:
http://codepen.io/anon/pen/qbqvgy
div {
width: 500px;
height: 500px;
background: url('http://2.bp.blogspot.com/-CmBgofK7QzU/TVj3u3N1h2I/AAAAAAAADN8/OszBhGvvXRU/s640/tumblr_lg7h9gpbtP1qap9qio1_500.jpeg');
}
div:hover {
background: url('https://media.giphy.com/media/V1T2JBmK03OFy/giphy.gifs');
}
<div>
</div>
Related
I have been using $().hide and $().show to make a smooth transition between images in a slideshow-like fashion. For example, when the right arrow key is pressed, the current image being displayed will slide to the left and disappear, the image will change, and it will slide into view from the right. This is the code I use for such a transition:
$('#mainImage').hide("slide", { direction: "left" }, 200);
$('#mainImage').show("slide", { direction: "right" }, 700);
setTimeout(function() { changeImg(pageNumberNew); }, 200);
The setTimeout() function is purely to control when in the transition the image source will change. The pageNumberNew variable is the URL of the image to be changed to. Here is the changeImg() function:
function changeImg(number) {
document.getElementById('mainImage').setAttribute('src', "/largefiles/2021roadatlas/Images/" + number + ".jpeg");
curPageNumber = number;
setWidth();
}
However, on the first transition of images, it will become very choppy, because the images haven't been loaded yet. I have tried various methods of preloading images, such as
Preloading images with JavaScript
Preloading images with jQuery
Waiting for image to load in JavaScript
JavaScript waiting until an image is fully loaded before continuing script
But none of these have worked.
Once an image has been loaded for the first time, navigating back to that image will be smooth. I would like a solution where these images can be preloaded before the user starts interacting, possibly loading each image before the transitions take place - causing for a slight delay in starting the animation, but allowing it to be smooth.
You can see what I have so far in action here, if you type in 13 and use the right and left arrow keys. The animations might not be choppy if you use desktop, try that website on mobile to see the issue.
TO BE CLEAR: I want a way to preload images in JavaScript, but I haven't been able to use the normal methods of preloading images, as described above.
The reason it is loading so slow is the large image. You should make the image size of the original photo smaller. I can see that the original size is around 5000 x 6500 and you are scaling it down to around 1000 x 600. The original image is unnecessarily big which causes the slow load.
I am trying to find a more modern solution that doesn't use jQuery as I am using React (Gatsbyjs specifically).
I have a website with multiple image carousels that contain high res images.
The issue is the each image carousel only show one image at a time, so only when the user navigates to the next image does the image get fetched, this results in a choppy loading appearance.
I have tried researching online with onLoad and load event listeners but none seem to have worked so far because they only load the image that is currently being shown by the carousel, instead of all of the images in the carousel.
If there is a way to first load all the images, then set the state to true, and only after the state is true, then the rest of the DOM appears onto the screen, that would be perfect.
Any suggestions? Thanks.
Website in question: https://dev--yachtgamechanger.netlify.com/
As Lonnie Best said, I ended up using Promise.all() to capture the loads of the images.
Just in case anyone else want to check it out:
https://codesandbox.io/s/react-image-preload-ptosn
I guess that your lib is using lazy load approach. And it's really good when dueling with high res images.
You still can change the approach to load all the images before rendering the UI, by going into the carousel component, change the rendering behavior by checking whether all images be loaded or not before render.
Updated: Because you are using gatsby-image, so just use this property:
loading: "eager". For EX:
<Img
fixed={data.file.childImageSharp.fixed}
alt="Gatsby Docs are awesome"
loading="eager"
/>
https://www.gatsbyjs.org/packages/gatsby-image/
You can ensure that an image is pre-downloaded 100% well before it gets displayed to the screen.
Simply create an Image element and set its src property to the URL where the image is located. Then use the image's onload event to detect when it is ready for instant display.
// Image to Pre-Download:
var image = new Image();
console.time("Image Fully Downloaded in");
image.src = "https://www.nasa.gov/sites/default/files/thumbnails/image/pia24870.jpeg";
image.onload = function()
{
console.timeEnd("Image Fully Downloaded in");
console.log("Image is ready for viewing.");
clearInterval(interval);
progress.parentNode.replaceChild(btn, progress);
}
// Fake Progress Indicator:
let progress = document.createElement("progress");
progress.value = 3;
progress.max = 100;
progress.textContent = "Fake Progress";
document.body.appendChild(progress);
let interval = setInterval(()=>
{
if (progress.value === 99)
{
progress.value = 0;
}
else
{
progress.value = progress.value + 1;
}
},50)
// Button to Replace Progress Indicator:
let btn = document.createElement("button");
btn.textContent = "View Entire Image Instantly";
btn.addEventListener('click',function()
{
this.parentNode.replaceChild(image, this);
});
img { max-width: 100%; }
<p>Only after the image is completely downloaded, will you see the button to view it:</p>
Based on this concept, you could pre-load/queue as many images as you like into image objects, so that they are ready to be displayed instantly (well before the user decides to view the next image). Here's an example where I'm switching between preloaded images automatically (so fast that it looks like an animated gif -- but it is actually 27 separate images from 27 different URL locations): See statue example and view source.
I have a video (let's call it composite video) composed by multiple other videos concatenated using some pattern. For example, see the screenshot of the videos below, composed by two and four other videos, respectively:
However, I need to display it differently: One main, larger, video and N-1 video thumbnails, where N is the total number of videos. Here are this other display corresponding to the videos above:
To display the main I'm using a combination of HTML and CSS to position the video I want in the larger div. It runs smoothly, no matter the number of videos in the composite videos.
To display the thumbnails, I'm using <canvas> to draw the parts I want:
video.addEventListener('play', function() {
(function loop() {
drawThumbnails();
setTimeout(loop, 1000 / 30); // drawing at 30fps
})();
}, false);
function drawThumbnails() {
for (var i = thumbs.length - 1; i >= 0; i--) {
drawThumbnail(thumbs[i]);
};
}
function drawThumbnail(thumb) {
var thumbNumber = Number(thumb.id.match(/\d+/g));
var canvasContext = thumb.getContext('2d');
var thumbCoordinates = getVideoCoordinates(thumbNumber);
var srcX = thumbCoordinates.column * videoWidth;
var srcY = thumbCoordinates.row * videoHeight;
canvasContext.drawImage(
video, srcX, srcY, videoWidth, videoHeight, // Source
0, 0, thumb.width, thumb.height); // Destination
}
It was working well for 3 (sometimes 4) videos. However, as the number of videos in the composite video increases, the videos in the thumbnails start to freeze and run not in a smooth way. This is probably happening because there's too much image processing being done at the same time.
I think the proper way to do it is, somehow, using <video> and methods specific for videos, not for images. I've also tried to use the same src in the multiple <video> tags (one for each thumbnail) and add eventListeners to play/pause the videos in the thumbnails once the main video is played/paused. That's not very efficient, particularly because videos can get out of sync sometimes, when seeking/buffering.
Is there a way of using only one video in multiple <video> tags and use only one of them (in my case, the one that contains the main video) to control all the others? In case there's no way of doing that, is there an alternative approach for my problem?
Thanks a lot,
P.S. Having multiple, separated, videos is not an option in my situation. It would take a very long time to process the input video and divide it in multiple videos.
You can certainly reference the same video across multiple video elements. Cloning the original and appending them as thumbnail videos might alleviate some of the tedium.
Iterating over the thumbnails and .play()ing them should be fine so long as you set their currentTime with that of the main video prior to playing, to minimize drift. There may be some need to wait for canplay to fire on the main video and/or the thumbnails depending on the exact experience you're looking to deliver.
If each thumbnail is given a parent container you could possibly position the video element serving as your thumbnail such that only the portion of the video you care to see is visible, clipping the rest.
FWIW, CSS masking might be of interest to you as a performance optimization if it helps the compositing performance.
You will need to manually coordinate playing/pausing all of the video elements, but that should be easy enough to do with a facade object that handle the play pause of all the "linked" video elements.
I know I'm posting late, and you may have already found an answer. However, if anyone else comes across this question, here is my answer:
You can use multiple video elements with the same source. The way to do it is with css.
.wrapper {
height: /*height of one video*/;
width: /*width of one video*/;
overflow: hidden;
}
video {
position: relative;
top: /*height offset*/;
left: /*width offset*/;
}
And HTML
<div class="wrapper">
<video src="myvideo.mp4"></video>
</div>
So, if I was doing the top right video, and each one was 250px by 250px, I would set my wrapper height and width to 250px and my video top to 0px and my video left to 250px
What's the format of the main video? Is it an on demand mp4/webm file?
If you still want to go with your approach of grabbing frames and paint them but is facing performance issues, consider using web workers for the heavy jobs. Here you can find some examples of video/canvas manipulation with web workers.
I have a button and an image and want them to change color onmouseover.
The button changes color fine:
<script>
function secondColor(x) {
x.style.color="#000000";
}
function firstColor(x) {
x.style.color="#ffaacc";
}
</script>
<input onmouseover="secondColor(this)" onmouseout="firstColor(this)" type="submit"><br>
How can I do the same thing with the image? Is there any way:
<img src="..." ......
Or do I have to have a second image to replace the first one onmouseover and this is the only way?
If you don't care that much about supporting older browsers, you could use the new CSS3 filter brightness. In chrome, you could write something like this:
var image = document.getElementById('img');
image.addEventListener('mouseover', function() {
image.setAttribute('style','-webkit-filter: brightness(1.5)');
}, false);
image.addEventListener('mouseout', function() {
image.setAttribute('style','-webkit-filter: brightness(1.0)');
}, false);
I don't recommend this approach, though. Using another picture while hovering would be a better solution.
I know that this is old, but you don't need two images. Checkout my example using one image.
You can simply change the position of the background image.
<div class="changeColor"> </div>
JavaScript
var dvChange = document.getElementsByClassName('changeColor');
dvChange[0].onmouseover = function(){
this.style.backgroundPosition = '-400px 0px';
}
dvChange[0].onmouseout = function(){
this.style.backgroundPosition = '0px 0px';
}
CSS
.changeColor{
background-image:url('http://www.upsequence.com/images/multibg.png');
width:400px;
height:400px;
background-position: 0px 0px;
}
.changeColor:hover{
background-image:url('http://www.upsequence.com/images/multibg.png');
width:400px;
height:400px;
background-position: -400px 0px;
}
You can also try changing the opacity of the images onmouseover and onmouseout.
I don't have an example for that, but its super easy to find and I am sure it has be answered already on stack exchange somewhere.
In the JSFiddle below there is Javascript and non-Javascript examples.
http://jsfiddle.net/hallmanbilly/gtf2s8ts/
Enjoy!!
I think you have to use a second image. I recently cam across the following article describing how to do image crossfading on hover using css. Crossfading Image Hover Effect
You can change image SRC on mouse over, you can load two images and use fade effects to "change" them. But better, you can use image as DIV background, make sprite and just move BG on mouse over.
Loading of two different images bring you to disappearing when hover and second image loading. Better do not use JS at all. Make sprite from two images, put it as BG of DIV and write two CSS for DIV, normal and when hover.
If you have access to JQuery use hover function. If you want to change image
$('#imageid').hover(function(){
//change image or color or opacity
$(this).attr('src', newImageSrc);
});
add this function in document ready function.
I noticed that when I do something like this (with jQuery, but I don't think it matters):
$("#myDiv").html("<img src='/image.png'/> this is my image.");
The browser displays the text first, and then the image is loaded, and shifts the text to the right which creates a horrible flickering effect.
The image doesn't appear to be cached by the browser. Any idea why ? How can I avoid this phenomena when loading images into the DOM ?
How can I avoid this phenomena when loading images into the DOM ? there are two major methods (may be more :))
1) Set the actual size of the img <img with='20' height='20' src='...' /> or via CSS style.
2) Use image preload and insert your code only when image is loaded
var img = new Image();
$(img).load(function(){
$("#myDiv").append($(this))
.append(document.createTextNode("this is my image.");
// or your way, browser should take image from cache
$("#myDiv").append("<img src='/image.png'/> this is my image.");
}).attr('src', '/image.png');
ps: there is a serious bag in SO engine - code formatting does not want to combine with numbered listing. So I removed the list.
Preload the image before attaching it:
$("<img>", {
load: function() {
$("#myDiv").empty().append( this, "this is my image." );
},
src: "/image.png"
});
preload your images like this
var images = [
'/path/to/some/image1.png',
'/path/to/some/image2.png'
];
$(images).each(function() {
var image = $('<img />').attr('src', this);
});
Images may render a little slower that text, even if cached. If you know the dimensions of the image add height and width attributes to the image and then it won't jump around.