<template>
<view>
<!-- 顶部图片 -->
<view class="parent">
<!-- 1:canvas 方式 -->
<view style="width:750rpx;height:540rpx">
<!-- canvas 偏移隐藏 -->
<canvas id="myCanvas" canvas-id="myCanvas" style="width:750rpx;height:540rpx" class="myCanvas"></canvas>
<!-- 加载canvas图片 -->
<image v-if="canvasImg!=''" class="animated fadeIn" :src="canvasImg" mode="aspectFill" style="width: 100%;height:540rpx"></image>
</view>
<!-- 2:纯css方式 -->
<!-- <view class="position-relative clip">
<image class="animated fadeIn" :src="fileUrl+bgimg" mode="aspectFill" style="width: 100%;height:540rpx"></image>
</view> -->
</view>
</view>
</template>
<script>
export default {
data() {
return {
canvasImg:'',
nowPx:0,
fileUrl:'全局文件域名/',//this.$sysconfig.fileUrl
bgimg:'图片路径'
}
},
onReady() {
//获取系统信息
uni.getSystemInfo({
success:res=>{
//单位转换,1rpx 等于多少 px
this.nowPx = res.windowWidth / 750
}
})
//初始化顶部图片
this.initTopImg(false)
},
methods: {
//设置顶部canvas并转成图片
setTopImg(){
let that = this
let nowPx = this.nowPx
//创建 canvas 绘图上下文
const ctx = uni.createCanvasContext('myCanvas')
//清空画板
ctx.clearRect(0,0,750*nowPx,540*nowPx)
ctx.beginPath();//创建路径
ctx.moveTo(0,0);//起始点,不写也行,个人习惯
ctx.quadraticCurveTo(750*nowPx,0,750*nowPx,0);//二次贝塞尔曲线,位移到右上角
ctx.quadraticCurveTo(750*nowPx,0,750*nowPx,540*nowPx/2);//二次贝塞尔曲线,位移到右边线中间点
ctx.bezierCurveTo(750*nowPx,540*nowPx,0,100,0,540*nowPx);//三次贝塞尔曲线,两段弧形位移到左下角
ctx.quadraticCurveTo(0,0,0,0);//二次贝塞尔曲线,回到起始点
ctx.clip();//裁切
let img = this.fileUrl+'uploads/1.png' //图片地址
//下载图片(小程序不能直接用网络图片绘制,H5可以,也可自行判断执行)
uni.downloadFile({
url:img,
success:(res)=>{
console.log(res)
// 加载图像并绘制
ctx.drawImage(res.tempFilePath, 0, 0,750*nowPx,540*nowPx)
// 取消剪切路径
ctx.restore();
//绘制到画板
ctx.draw();
//延迟100毫秒执行
setTimeout(a=>{
//canvas转图片
uni.canvasToTempFilePath({
x: 0,
y: 0,
canvasId: 'myCanvas',
success: (res)=>{
// 在H5平台下,tempFilePath 为 base64
that.canvasImg = res.tempFilePath
}
})
},100)
}
})
},
//初始化顶部图片,resetImg:boolean,用户修改背景图时传true,重载canvas图片,否则只有canvas图片为空的时候执行
initTopImg(resetImg){
if(resetImg){
return this.setTopImg()
}
if(this.canvasImg==''){
return this.setTopImg()
}
},
}
}
</script>
<style>
/* canvas 偏移隐藏 */
.myCanvas{
position: absolute;
right:1000rpx;
}
/* 使用CSS裁剪图片,狗啃式。。 */
.clip{
clip-path: polygon(0 0, 100% 0,100% 50%,98.84% 57.57%, 97.39% 63.31%, 95.6% 67.79%, 93.5% 70.98%, 91.12% 72.87%, 88.5% 74%,85% 75%,15% 75%,14% 75.2%,13.2% 75.6%,12% 76%,11% 76.5%,10% 77%,9% 78%,8% 79%,7% 80.5%,6% 82%,5% 83.2%,4% 85%,3% 87%,2% 89%,1% 92%,0 100%);
}
.parent {
/* 使用filter生成阴影 */
filter: drop-shadow(2rpx 6rpx 16rpx rgba(0,0,0,0.5));
}
</style>
uniapp一个异形背景图
最新推荐文章于 2024-10-18 17:51:23 发布