项目场景:

提示:这里简述项目相关背景:

在用uniapp做微信小程序的时候,需要一张背景图,用的是当时做app的时候的框架,但是,在class的样式中background-image失效了,查了后才知道,微信小程序不支持在class中使用background-image,但是可以在标签中使用,而且需要图片路径是base64编码格式的。


解决方案:

提示:这里填写该问题的具体解决方案:

1:图片转换base64编码的工具

npm i image-tools --save

//引入使用
import { pathToBase64, base64ToPath } from 'image-tools'


2:使用函数进行转换

//this.imgUrl 图片路径 /static/img/bg1.png
pathToBase64(this.imgUrl).then(res=>{
    this.bgImgBase64=res
})

3:在标签中使用

//width height 要设置 
/*
background-attachment 属性值说明
background-attachment 属性有三个主要的可选值,每个值对应不同的效果:
scroll:默认值,背景图像会随着页面内容滚动。
fixed:背景图像固定在视窗中,不会随页面滚动。
local:背景图像与元素内容一起滚动,但仅限于该元素的滚动区域内。
*
/

<view 
	:style="{
		width:'100%',
		height:'100%',
		backgroundImage:'url('+bgImgBase64+')',
		backgroundRepeat: 'no-repeat',
		backgroundPosition: 'center',
		backgroundSize: '100% 100%',
		backgroundAttachment: 'fixed',
	}"
	class="index-content">
......
</view>

4:效果图

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐