本文實例為大家分享了vue實現輪播圖幀率播放的具體代碼,供大家參考,具體內容如下
需求
傳入一個數組,數組中放的是目錄名稱,通過本目錄名稱,讀取文件目錄下的所有圖片,并循環播放,形成一個每1s播放多少張圖片的效果,最后目錄播放完畢后,在跳到第一個目錄循環播放。
核心: 用 webpack的一個API require.contex讀取目錄下的文件名,具體想了解的可以查一查。
代碼
HTML
1
2
3
4
5
6
7
8
9
|
< template > < div id = "imgPlay" ref = "container" :style = "[style]" > < img :src = "imgsrc" :style = "[{height:style.height,width:style.width}]" > < div id = "but" > < button @ click = "start()" >開始</ button > < button @ click = "stop()" >停止</ button > </ div > </ div > </ template > |
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
|
<script> export default { name: 'ZxImgPlay' , data () { return { style:[ width: "50px" , height: "50px" ], interval: null , // 定時器id flag: true , // 定時器的開關 setIntervalNumber: 0, // 當前展示的圖片下標 imgsrc: "" , // 要展示的圖片路徑 imgUrls: [], // 所有的圖片路徑 frameRate: 0 // 幀率 } }, computed: {}, watch: {}, created () { }, mounted () { this .zxInit() }, beforeDestroy () { }, methods: { zxInit () { // 這里的 this.DisplayParam 是公司內部的一套東西,混入的對象 // this.DisplayParam.frameRate 是一個數組["目錄名1","目錄名2"] // this.DisplayParam.imgUrls 是死圖當沒有目錄的時候就用死圖 // this.DisplayParam.frameRate 是傳入的幀率 this .frameRate = this .DisplayParam.frameRate && (1000 / this .DisplayParam.frameRate) this .imgUrls = this .DisplayParam.imgUrls this .DisplayParam.imageFileName != 0 ? this .readdir( this .DisplayParam.imageFileName) : this .showImages( true ) }, start () { if ( this .flag) return this .showImages() this .flag = true }, stop () { this .flag = false clearInterval( this .interval) }, readImages (imageFileName, _A) { this .stop() let req = require.context( "@/../static/images" , true , /\.(?:bmp|jpg|gif|jpeg|png)$/).keys(); let path = new RegExp(imageFileName[_A]) req.forEach(item => { if (path.test(item)) { this .imgUrls.push({ img: "@/../static/images/" + imageFileName[_A] + item.substring(item.lastIndexOf( '/' )) }) } }) this .showImages() }, readdir (imageFileName) { this .imgUrls = [] for (let i = 0; i < imageFileName.length; i++) { this .readImages(imageFileName, i) } }, showImages (_B) { if (_B) this .imgUrls = this .imgUrlsSort( this .imgUrls, 'sort' ) console.log( this .imgUrls) this .interval = setInterval( this .setIntervalFun, this .frameRate) }, imgUrlsSort (ary, key) { return ary.sort((a, b) => { let x = a[key]; let y = b[key]; return ((x < y) ? -1 : (x > y) ? 1 : 0) }) }, setIntervalFun () { if ( this .setIntervalNumber >= this .imgUrls.length) { this .setIntervalNumber = 0 } this .imgsrc = this .imgUrls[ this .setIntervalNumber++].img || '' } } } </script> |
問題
上述這么做已經實現了功能,但是目前來說是發現了兩個問題
1、require.context() 這個API它的第一個參數不能用一個可變的值,比如變量,會有警告。
2、上述代碼一直更換圖片的src實現的,也就是說每次換src時都會發送http請求獲取圖片,導致了內存不會被釋放一直增加。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/qq_44393247/article/details/113147062