嗨,我想知道是否有人知道如何使两张图像以半秒的间隔在彼此之间转换? “开始”按钮开始播放动画,“停止”按钮将停止播放当前显示的动画。如果您可以告诉我如何至少使动画变得不适,那就开心点。停止它只是一种奖励。
var start;
function setTime()
{
start = 1;
carSchedule = setInterval(carChange, 500);
}
function carChange()
{
var imageData;
if (start == 1)
{
imageData = document.getElementById("car");
imageData.src = "https://dummyimage.com/600x400/000/fff";
}
else if(start == 2)
{
imageData = document.getElementById("car");
imageData.src = "https://dummyimage.com/600x400/ff00ff/0011ff";
}
}
<button onClick = "carChange()">Start Animation</button>
<button onCLick = "stop()">Strop Animation</button>
<br/>
<img id="car">
答案 0 :(得分:2)
您可以将图像存储在Array
中,并使用setInterval
遍历它们:
let srcs = [
'http://www.catster.com/wp-content/uploads/2017/08/A-fluffy-cat-looking-funny-surprised-or-concerned.jpg',
'https://images.pexels.com/photos/617278/pexels-photo-617278.jpeg?auto=compress&cs=tinysrgb&h=350'
];
//Preload your images
let imgs = srcs.map(src => {
let img = new Image();
img.src = src;
return img
});
let img = document.getElementById('car');
let current = 0; //Current image displayed
let interval;
const carChange = () => {
interval = setInterval(() => {
if (current + 1 > srcs.length - 1) current = 0;
else current++;
img.src = imgs[current].src
}, 500);
}
const stop = () => {
clearInterval(interval);
}
<button onClick="carChange()">Start Animation</button>
<button onCLick="stop()">Stop Animation</button>
<p><img id="car" /></p>