以下是一个简单的微信小程序拉伸图片四个角变形的示例代码:
wxml文件:
```html
<view class="container">
<canvas class="canvas" canvas-id="canvas"></canvas>
</view>
```
js文件:
```javascript
Page({
data: {
imageSrc: '', // 图片路径
startX: 0,
startY: 0,
imgWidth: 0,
imgHeight: 0,
isMoving: false,
},
onLoad() {
// 加载图片
wx.getImageInfo({
src: 'https://example.com/image.png',
success: (res) => {
this.setData({
imageSrc: res.path,
})
this.initCanvas()
},
})
},
// 初始化canvas
initCanvas() {
const ctx = wx.createCanvasContext('canvas', this)
ctx.drawImage(this.data.imageSrc, 0, 0, 300, 300)
ctx.draw()
// 获取图片信息
wx.getImageInfo({
src: this.data.imageSrc,
success: (res) => {
this.setData({
imgWidth: res.width,
imgHeight: res.height,
})
},
})
},
// 触摸开始
touchStart(e) {
const { x, y } = e.touches[0]
this.setData({
startX: x,
startY: y,
isMoving: true,
})
},
// 触摸移动
touchMove(e) {
if (!this.data.isMoving) {
return
}
const { x, y } = e.touches[0]
const offsetX = x - this.data.startX
const offsetY = y - this.data.startY
const ctx = wx.createCanvasContext('canvas', this)
// 左上角
if (offsetX < 0 && offsetY < 0) {
ctx.drawImage(this.data.imageSrc, x, y, -offsetX, -offsetY, 0, 0, -offsetX, -offsetY)
}
// 右上角
else if (offsetX > 0 && offsetY < 0) {
ctx.drawImage(this.data.imageSrc, 0, y, this.data.imgWidth + offsetX, -offsetY, offsetX, 0, this.data.imgWidth + offsetX, -offsetY)
}
// 左下角
else if (offsetX < 0 && offsetY > 0) {
ctx.drawImage(this.data.imageSrc, x, 0, -offsetX, this.data.imgHeight + offsetY, 0, offsetY, -offsetX, this.data.imgHeight + offsetY)
}
// 右下角
else {
ctx.drawImage(this.data.imageSrc, 0, 0, this.data.imgWidth + offsetX, this.data.imgHeight + offsetY, offsetX, offsetY, this.data.imgWidth + offsetX, this.data.imgHeight + offsetY)
}
ctx.draw()
},
// 触摸结束
touchEnd() {
this.setData({
isMoving: false,
})
},
// 保存图片
saveImage() {
wx.canvasToTempFilePath({
x: 0,
y: 0,
width: 300,
height: 300,
destWidth: 300,
destHeight: 300,
canvasId: 'canvas',
success: (res) => {
wx.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
})
},
}, this)
},
})
```
css文件:
```css
.container {
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height: 100vh;
}
.canvas {
width: 300rpx;
height: 300rpx;
border: 1px solid #ccc;
}
```
注:以上代码仅作为示例,实际应用可能需要根据具体需求进行修改。