html5控制gif图的播放和暂停,使用JS和canvas实现gif动图的停止和播放代码
时间: 2024-03-21 09:42:59 浏览: 20
以下是一个简单的用canvas和JS控制gif图播放和暂停的示例代码:
HTML:
```html
<canvas id="myCanvas"></canvas>
<button id="playBtn">播放</button>
<button id="pauseBtn">暂停</button>
```
JS:
```javascript
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var img = new Image();
img.src = "example.gif";
var isPlaying = true;
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0);
if (isPlaying) {
setTimeout(draw, 50);
}
}
img.onload = function() {
canvas.width = img.width;
canvas.height = img.height;
draw();
};
document.getElementById("playBtn").addEventListener("click", function() {
isPlaying = true;
draw();
});
document.getElementById("pauseBtn").addEventListener("click", function() {
isPlaying = false;
});
```
这段代码首先创建了一个canvas元素和两个按钮。然后创建了一个Image对象来加载gif图像。在画布上使用drawImage方法绘制图像,并在isPlaying为true时使用setTimeout函数不断重绘画布,形成gif动画效果。当点击播放按钮时,设置isPlaying为true并调用draw函数;当点击暂停按钮时,设置isPlaying为false,停止动画。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)