项目需求:图片以轮播图的形式可左右滑动,点击旋转可以顺时针旋转当前展示的图片。
思路:用swiper实现轮播,用canvas实现旋转并把旋转后的画布转成图片替换当前展示的图片。
页面相关功能UI图:
wxml代码:
<view class="card-general">
<view>鲜牛肉检测报告</view>
<swiper class="image-wrapper" circular bindchange="imageChange">
<block wx:for="{{imgUrls}}" wx:key="index">
<swiper-item>
<image mode="aspectFit" src="{{item.playUrl}}"></image>
</swiper-item>
</block>
</swiper>
<view class="image-pages">
<view>{{currentIdx+1}}/{{imgTotal}}</view>
<view bind:tap="handleRotate" style="background: #EEE;width: 50rpx;height: 62rpx"></view>
</view>
</view>
<canvas wx:if="{{showCanvas}}" canvas-id="canvas" style="position: absolute;right:-3000px;height:{{canvasHeight}}; width: {{canvasWidth}}"></canvas>
js代码:
//点击旋转
handleRotate(){
this.setData({
showCanvas:true //showCanvas设置是否展示来清除之前绘制的,不然会有bug,原因还不懂
})
const currentTarget = this.data.imgUrls[this.data.currentIdx]
//如果已经旋转了270度了,此次点击回复原来的图片
if(currentTarget.transNum===3){
const setImage = `imgUrls[${this.data.currentIdx}]`
setTimeout(()=>{ //设置定时器是为了和后面旋转的时间保持一致
this.setData({
[setImage]: {
originUrl:currentTarget.originUrl,
playUrl:currentTarget.originUrl,
transNum:0
}
})
},400)
}else{
//以下数字是由于页面装图片的盒子大小为662px*820px
wx.getImageInfo({
src:currentTarget.playUrl,
success: imgInfo=> {
let newW,newH
//设置旋转后的图片最长宽是以哪个为参考
if(imgInfo.height/imgInfo.width>820/662){
newW = 662
newH = 662/imgInfo.height*imgInfo.width
}else{
newW = 820*imgInfo.height/imgInfo.width
newH = 820
}
this.setData({
canvasWidth:newW+'px',
canvasHeight:newH+'px'
})
canvas.save()
canvas.translate(newW, 0);
canvas.rotate(90 * Math.PI / 180);
canvas.drawImage(currentTarget.playUrl, 0, 0, newH,newW);
canvas.draw(
false,
this.setNewImg(newW, newH)
)
}
})
}
},
//把canvas绘制的图片保存为新的图片并替换展示的链接
setNewImg(imgWidth, imgHeight){
setTimeout(()=>{
wx.canvasToTempFilePath({
canvasId: 'canvas',
x: 0,
y: 0,
destWidth: imgWidth,
destHeight: imgHeight,
success: (res)=> {
const currentImg = this.data.imgUrls[this.data.currentIdx]
const setImage = `imgUrls[${this.data.currentIdx}]`
this.setData({
[setImage]:{
originUrl:currentImg.originUrl,
playUrl:res.tempFilePath,
transNum:currentImg.transNum+1
},
showCanvas:false
})
}
})
},400)
}