uniapp canvas 一张图片作为背景,另一张图片可以在画布内拖动改变位置,拖动完毕后可以通过按钮保存该画布图片到本地的代码
时间: 2024-05-22 19:16:33 浏览: 120
<template>
<view class="container">
<view class="canvas-container">
<canvas canvas-id="myCanvas" :style="{width: canvasWidth+'px', height: canvasHeight+'px'}"></canvas>
<image src="/static/background.jpg" mode="aspectFill" :style="{width: canvasWidth+'px', height: canvasHeight+'px'}"></image>
<image v-if="dragging" :src="dragImage" :style="{left: dragLeft+'px', top: dragTop+'px'}" @touchmove.stop.prevent="onTouchMove"></image>
</view>
<view class="button-container">
<button class="btn" @tap="saveImage">保存图片</button>
</view>
</view>
</template>
<script>
export default {
data() {
return {
canvasWidth: 300,
canvasHeight: 300,
dragImage: '/static/drag.jpg',
dragLeft: 0,
dragTop: 0,
dragging: false,
}
},
mounted() {
this.drawCanvas()
},
methods: {
drawCanvas() {
const ctx = uni.createCanvasContext('myCanvas', this)
ctx.draw()
},
onTouchMove(event) {
const { pageX, pageY } = event.changedTouches[0]
const x = pageX - this.dragImageWidth / 2
const y = pageY - this.dragImageHeight / 2
this.dragLeft = x
this.dragTop = y
},
saveImage() {
uni.canvasToTempFilePath({
canvasId: 'myCanvas',
success: (res) => {
uni.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success: () => {
uni.showToast({
title: '保存成功',
})
},
fail: () => {
uni.showToast({
title: '保存失败',
icon: 'none',
})
},
})
},
fail: () => {
uni.showToast({
title: '生成图片失败',
icon: 'none',
})
},
}, this)
},
},
computed: {
dragImageWidth() {
return 50
},
dragImageHeight() {
return 50
},
},
}
</script>
<style>
.container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
}
.canvas-container {
position: relative;
}
.button-container {
margin-top: 20px;
}
.btn {
padding: 10px 20px;
background-color: #007aff;
color: #fff;
border-radius: 5px;
}
</style>
阅读全文