一、image标签是可以显示本地地址的图片的。
<image src="{{spriteBackground}}" />
.js
Page({
data: {
spriteBackground:"/statics/home-icon.png",
}
})
二、background引用图片用本地路径的地址在开发者工具上是正常的,手机上就不显示了,因为小程序的背景图片只能展示base或网络地址的图片。
本地图片转成base64的方法:
使用微信小程序文档API
wx.getFileSystemManager().FileSystemManager.readFile(Object object)
注意:版本库要在1.9.9以后的版本才支持
<view class="img" style="background-image:url({{spriteBackground}}); background-position:{{item.position}}" />
Page({
data: {
spriteBackground:"/statics/home-icon.png"
}
onLoad: function (options) {
var that = this;
let base64 = wx.getFileSystemManager().readFileSync(this.data.spriteBackground, 'base64');
that.setData({
'spriteBackground': 'data:image/jpg;base64,' + base64
});
},
})
补充:
方法定位:https://developers.weixin.qq.com/miniprogram/dev/api/file/FileSystemManager.html
wx.getFileSystemManager().readFile({
filePath: '图片的相对路径',
encoding: 'base64', //编码格式
success: res => { //成功的回调
console.log('data:image/png;base64,' + res.data)
}
})