gpt4 book ai didi

javascript - 使用纯 JavaScript 在鼠标悬停时播放一系列 GIF 动画图像

转载 作者:行者123 更新时间:2023-11-30 11:30:02 24 4
gpt4 key购买 nike

我有一个要求,我有一个 <image>链接到一系列动画 gif 图像的标签。

我想在 mouse over 上播放那些动画 (gif)状态,一个接一个(像一个播放列表)。然后在mouse Out我想返回一些原始 img 源(比如静态海报图像,等待用户 rollover 状态)。

请在下面找到我试过的伪代码:

function nextSlide() {
document.getElementsByTagName('img').setAttribute('src', slides[currentSlide]);
currentSlide = (currentSlide + 1) % slides.length;
}

document.getElementsByTagName('img').addEventListner('mouseover',function(){
slides = gifImages;
var slideInterval = setInterval(nextSlide,1000);
});
document.getElementsByTagName('img').addEventListener('mouseout', function(){
document.getElementsByTagName('img').src = originalImage;
});

使用上述代码的挑战(修复):

1. 我希望 gif 图像仅在其动画完成后才被替换,但在我使用 setInterval 时,它会在每次计时器延迟后被替换。 .

2.mouse out它不会返回到原始图像。

3.第一张图片也在 1 秒后加载(因为这是 setInterval 的速率)。

请告诉我是否有任何方法可以实现此目的。

更新:

  • 问题 2 和 3 已解决。现在我面临的唯一问题是播放 gif 图片集。

最佳答案

很多小时后,我得到了我自己的问题的答案。
我得到了一个代码片段来获取 GIF 图像的持续时间。一旦我有了 GIF 图像的持续时间,我就可以在 GIF 图像的持续时间之后设置间隔。

    function getGIF(url) {
function downloadFile(url, success) {
let xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'arraybuffer';
xhr.setRequestHeader('Cache-Control', 'no-cache');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (success) {
success(xhr.response);
}
const file = new Blob([xhr.response], {type:'image/jpeg'});
}
};
xhr.send(null);
}

downloadFile(url, function (data) {
let d = new Uint8Array(data);

let bin = null;
let duration = 0;
for (let i = 0; i < d.length; i++) {
bin += String.fromCharCode(d[i]);

// Find a Graphic Control Extension hex(21F904__ ____ __00)
if (d[i] === 0x21 &&
d[i + 1] === 0xF9 &&
d[i + 2] === 0x04 &&
d[i + 7] === 0x00) {
// Swap 5th and 6th bytes to get the delay per frame
let delay = (d[i + 5] << 8) | (d[i + 4] & 0xFF);

// Should be aware browsers have a minimum frame delay
// e.g. 6ms for IE, 2ms modern browsers (50fps)
duration += delay < 2 ? 10 : delay;
}
}
});
return duration;
}


感谢 codepen,我从那里得到了解决方案:LINK
引用:

  1. > http://justinsomnia.org/2006/10/gif-animation-duration-calculation/
  2. > http://www.w3.org/Graphics/GIF/spec-gif89a.txt

关于javascript - 使用纯 JavaScript 在鼠标悬停时播放一系列 GIF 动画图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46599605/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com