需求分析

图片加载需要很长时间才能显示,所以需要一张图片进行占位。

演示效果

高斯模糊占位图演示图

解决方案分析

1. 在弱网环境下需要一张超低分辨率的图片,作为占位图。
这里可以使用七牛云的API,获取超低分辨率的图片。
https://apkj-static.apyfc.com/1610523307609502.jpeg?imageView2/3/q/1
imageView2:代表使用的API
3: 代表mode
q/1: 表示将原始图片压缩至 1%

获得图片如下:

高斯模糊占位图

2. 使用css3 高斯模糊,对图片进行处理,让图片过渡自然。

1
2
3
4
5
6
7
8
<!-- index.html -->
<img src="https://apkj-static.apyfc.com/1610523307609502.jpeg?imageView2/3/q/1"></img>

<style>
img {
filter: blur(5px);
}
</style>

效果如下:

高斯模糊占位图

3. 对原始图片增加事件监听

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!-- index.html -->
<img src="https://apkj-static.apyfc.com/1610523307609502.jpeg?imageView2/3/q/1"></img>
<img onload="loaded" src="https://apkj-static.apyfc.com/1610523307609502.jpeg"></img>

<script>
function loaded() {
// 触发过渡效果
// ...
}
</script>

<style>
img {
filter: blur(5px);
}
</style>

完整代码–以小程序为例

1
2
3
4
5
6
7
<!-- index.wxml -->
<div class="{{ showImg ? 'wrap wrap_show' : 'wrap' }}">
<!-- 占位图 -->
<image wx:if="{{ !showImg }}" src="{{imgUrl}}"></image>
<!-- 最终展示图 -->
<image bindload="loaded" class="{{ showImg ? '' : 'img' }}" src="{{imgUrl2}}"></image>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/* index.ts */
Page({
data: {
/** 带压缩为 1% 的模糊图 */
imgUrl: 'https://apkj-static.apyfc.com/1610523307609502.jpeg?imageView2/3/q/1',
/** 正常图片 */
imgUrl2: 'https://apkj-static.apyfc.com/1610523307609502.jpeg',
/** 控制图片显示 */
showImg: false
},
/** 图片加载完毕触发该方法 */
loaded() {
setTimeout(() => {
this.setData({ showImg: true })
}, 1000)
}
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/* index.wxss */
.wrap {
transition: filter 1s ;
transition-timing-function: linear;
filter: blur(5px);
}
.img {
position: absolute; z-index: -1;
top: 0;
left: 0;
width: 100%; height: 100%;
}
.wrap_show {
filter: blur(0);
}