点击(此处)折叠或打开
-
<view class='img' bindtap='img'>上传文件</view>
-
<canvas class='canvas' canvas-id='myCancas' style="width:{{width}}px;height:{{height}}px;background:red;"></canvas>
- <view class='img_box'><image wx:for="{{arr}}" src="{{item}}" mode='widthFix'></image></view>
点击(此处)折叠或打开
-
page{
-
position: relative;
-
}
-
.img_box{
-
/* display: flex;
-
justify-items: center;
-
align-items: center; */
-
text-align: center;
-
}
-
.canvas{
-
position:absolute;
-
top:-999999999999999999999rpx;
-
left:0;
-
- }
点击(此处)折叠或打开
-
// pages/upfile/upfile.js
-
const ctx = wx.createCanvasContext("myCancas", this)
-
Page({
-
-
/**
-
* 页面的初始数据
-
*/
-
data: {
-
arr:[]
-
},
-
-
/**
-
* 生命周期函数--监听页面加载
-
*/
-
onLoad: function (options) {
-
-
},
-
-
/**
-
* 生命周期函数--监听页面初次渲染完成
-
*/
-
onReady: function () {
-
-
},
-
-
/**
-
* 生命周期函数--监听页面显示
-
*/
-
onShow: function () {
-
-
},
-
-
/**
-
* 生命周期函数--监听页面隐藏
-
*/
-
onHide: function () {
-
-
},
-
-
/**
-
* 生命周期函数--监听页面卸载
-
*/
-
onUnload: function () {
-
-
},
-
-
/**
-
* 页面相关事件处理函数--监听用户下拉动作
-
*/
-
onPullDownRefresh: function () {
-
-
},
-
-
/**
-
* 页面上拉触底事件的处理函数
-
*/
-
onReachBottom: function () {
-
-
},
-
-
/**
-
* 用户点击右上角分享
-
*/
-
onShareAppMessage: function () {
-
-
},
-
img:function(e){
-
var that =this
-
wx.chooseImage({
-
success: function(res) {
-
console.log(res.tempFilePaths)
-
var img_arr = res.tempFilePaths
-
that.canvas_show(0,img_arr)
-
}
-
})
-
},
-
canvas_show: function (index, img_arr){
-
var that = this;
-
wx.showLoading({
-
title: '加载中',
-
icon:'loading'
-
})
-
if (index < img_arr.length){
-
wx.getImageInfo({
-
src: img_arr[index],
-
success: function (res) {
-
console.log("获取的图片结果", res)
-
var originHeight = res.height,
-
originWidth = res.width;
-
var maxWidth = 800,
-
maxHeight = 400;
-
// 目标尺寸
-
var targetWidth = originWidth,
-
targetHeight = originHeight;
-
//等比例压缩,如果宽度大于高度,则宽度优先,否则高度优先
-
if (originWidth > maxWidth || originHeight > maxHeight) {
-
if (originWidth / originHeight > maxWidth / maxHeight) {
-
// 要求宽度*(原生图片比例)=新图片尺寸
-
targetWidth = maxWidth;
-
targetHeight = Math.round(maxWidth * (originHeight / originWidth));
-
} else {
-
targetHeight = maxHeight;
-
targetWidth = Math.round(maxHeight * (originWidth / originHeight));
-
}
-
}
-
that.setData({
-
width: targetWidth,
-
height: targetHeight
-
},()=>{
-
setTimeout(()=>{
-
ctx.drawImage(img_arr[index], 0, 0, res.width, res.height, 0, 0, targetWidth, targetHeight);
-
ctx.draw(false, function (res) {
-
console.log(res)
-
//输出图片文件
-
new Promise((resolve, reject) => {
-
wx.canvasToTempFilePath({
-
canvasId: 'myCancas',
-
success: function (res) {
-
// console.log("生成图片的结果", res.tempFilePath)
-
resolve(res.tempFilePath)
-
}
-
}, this)
-
}).then(res => {
-
console.log("生成图片的结果", res)
-
that.setData({
-
arr: that.data.arr.concat(res)
-
})
-
-
index = index + 1;
-
that.canvas_show(index, img_arr)
-
wx.hideLoading()
-
})
-
})
-
-
},1000)
-
-
})
-
}
-
})
-
-
}
-
-
-
}
- })