<template>
<view class="">
<canvas canvas-id="myCanvas" id="myCanvas":style="canvasStyle" ></canvas>
<button @click="chooseImage">选择图片</button>
<image style="width: 100%;height: 300rpx;" :src="src" mode="widthFix"></image>
</view>
</template>
<script>
export default {
data() {
return {
src:'',
canvasParams: {
canvasWidth: 100, // 默认宽度
canvasHeight: 100, // 默认高度
}
};
},
computed: {
canvasStyle() {
return {
width: this.canvasParams.canvasWidth + 'px',
height: this.canvasParams.canvasHeight + 'px',
background:'#999',
}
}
},
methods: {
chooseImage() {
uni.chooseImage({
sourceType: ['all'],
success: async ({ tempFilePaths, tempFiles }) => {
this.src = tempFilePaths[0]
const imgFileArr = await this.uploadFilePromise(tempFilePaths[0])
}
})
},
uploadFilePromise(src) {
return new Promise((resolve, reject) => {
uni.getImageInfo({
src: src,
success: res=>{
this.canvasParams.canvasWidth = res.width;
this.canvasParams.canvasHeight = res.height;
this.$nextTick(()=>{
const ctx = uni.createCanvasContext('myCanvas', this);
const { canvasWidth, canvasHeight } = this.canvasParams
// 绘制前清空画布
ctx.clearRect(0, 0, canvasWidth, canvasHeight)
ctx.drawImage(src, 0, 0, canvasWidth, canvasHeight);
// 绘制完成后,导出为图片并上传
ctx.draw(true, () => {
uni.canvasToTempFilePath({
canvasId: 'myCanvas',
success: (res) => {
const tempFilePath = res.tempFilePath;
resolve(tempFilePath)
},
fail: (err) => {
console.error('导出图片失败:', err);
}
});
});
})
}
});
})
},
}
}
</script>
动态修改canvas之后,为什么绘制的图片只有初始的canvas大小呀?望大佬解惑
李钟硕 (作者)
十分感谢
2024-07-24 18:39