uniapp canvas 一张图片作为背景,另一张图片可以在画布内拖动改变位置,拖动完毕后可以通过按钮保存该画布图片到本地的代码
时间: 2024-06-02 22:14:23 浏览: 71
template:
<template>
<view>
<canvas canvas-id="myCanvas" style="width: 100%; height: 100%;"></canvas>
<view class="btn" @click="saveImage">保存图片</view>
</view>
</template>
script:
<script>
export default {
data() {
return {
bgImg: '', // 背景图片
moveImg: '', // 可移动图片
moveImgX: 0, // 可移动图片横向位置
moveImgY: 0, // 可移动图片纵向位置
canvasWidth: 0, // 画布宽度
canvasHeight: 0, // 画布高度
}
},
mounted() {
this.initCanvas()
},
methods: {
// 初始化画布
initCanvas() {
const that = this
uni.getImageInfo({
src: '背景图片路径',
success: function (res) {
that.bgImg = res.path
that.canvasWidth = res.width
that.canvasHeight = res.height
that.drawCanvas()
}
})
},
// 绘制画布
drawCanvas() {
const that = this
const ctx = uni.createCanvasContext('myCanvas')
// 绘制背景图片
ctx.drawImage(this.bgImg, 0, 0, this.canvasWidth, this.canvasHeight)
// 绘制可移动图片
if (this.moveImg) {
ctx.drawImage(this.moveImg, this.moveImgX, this.moveImgY, 100, 100)
}
ctx.draw()
},
// 移动可移动图片
moveImage(e) {
this.moveImgX = e.touches[0].x - 50
this.moveImgY = e.touches[0].y - 50
this.drawCanvas()
},
// 选择可移动图片
chooseImage() {
const that = this
uni.chooseImage({
success: function (res) {
that.moveImg = res.tempFilePaths[0]
that.drawCanvas()
}
})
},
// 保存画布图片
saveImage() {
const that = this
uni.canvasToTempFilePath({
canvasId: 'myCanvas',
success: function (res) {
uni.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success: function () {
uni.showToast({
title: '保存成功'
})
},
fail: function () {
uni.showToast({
title: '保存失败'
})
}
})
}
})
},
}
}
</script>
阅读全文