<template>
<view>
<canvas canvas-id="myCanvas" v-if="show"></canvas>
<button type="default" @click="seave" v-if="!show">点击</button>
<button type="default" @click="myimg" v-if="show">保存</button>
</view>
</template>
<script>
export default {
data() {
return {
show:false,
imgs:'../../static/logo.png',
text:'文字'
}
},
onLoad() {},
methods: {
seave(){
let _this = this
_this.show = true
const ctx = uni.createCanvasContext('myCanvas')
ctx.fillText('Hello', 20, 20)//描绘文本
ctx.fillText(_this.text, 50, 20)
ctx.drawImage(_this.imgs,50,50)//描绘图片
ctx.draw(false, (() => {
setTimeout(()=>{
uni.canvasToTempFilePath({
canvasId: 'myCanvas',
destWidth: _this.cropW*_this.canvasScale*2, //分享图片尺寸=画布尺寸1*缩放比0.5*像素比2
destHeight: _this.cropH*_this.canvasScale*2,
quality:1,
fileType:'jpg',
success: (res) => {
// console.log(res,'success')
uni.compressImage({
src: res.tempFilePath,
quality: 100,
success: res => {
const share_img=res.tempFilePath
uni.canvasToTempFilePath({
canvasId: 'myCanvas',
destWidth: _this.cropW*2, //展示图片尺寸=画布尺寸1*像素比2
destHeight: _this.cropH*2,
quality:1,
fileType:'jpg',
success: (res) => {
console.log(res.tempFilePath);
uni.setStorageSync('imgs',res.tempFilePath)
uni.hideLoading()
const img = res.tempFilePath
// _this.show = false
_this.$emit('confirm', {
share_img,
img
})
},
}, _this);
}
})
},
}, _this);
},500)
})())
},
myimg(){
uni.saveImageToPhotosAlbum({
filePath: uni.getStorageSync('imgs'),
success: function() {
uni.showToast({
icon: 'none',
position: 'bottom',
title: "图片已下载至【图库】,请打开【图库】查看", // res.tempFilePath
});
}
});
}
}
}
</script>
<style>
</style>
uni-app使用canvas生成图片并保存到相册
最新推荐文章于 2024-07-11 14:17:48 发布