imgW: '', // canvas 宽度
imgH: '', // canvas 高度
byclear: 1 // 比例,这里将iphon6- 375像素设置为1标准,以便在自适应上的转换
onReady() {
var that = this
// 根据屏幕的宽度计算标准比例值。这里讲375作为标准值
wx.getSystemInfo({
success: function(res) {
let byclear = res.screenWidth / 375
that.setData({
byclear
openAndDraw() { // 选择图片
var that = this
wx.chooseImage({
success: (res) => {
that.setData({
imgSrc: res.tempFilePaths[0],
checkwh(e) {
// 处理逻辑
在方法checkwh里面即可获取到图片宽高
checkwh(e){
// 实际宽度 e.detail.width 高度 e.detail.height
let whsrc = e.detail.height / e.detail.width
// 计算高宽,需要处理图片宽度小于屏幕宽度的时候 对应的canvas比例
checkwh(e){
// 实际宽度 e.detail.width 高度 e.detail.height
let whsrc = e.detail.height / e.detail.width
// 计算高宽,需要处理图片宽度大于屏幕宽度的时候 对应的canvas比例
let res = this.data.res
let byclear = this.data.byclear
const ctx = wx.createCanvasContext('canvasIn', this);
// 对画布进行缩放,注意scale两个参数保持一致,即缩放比例都是一样的。保证宽高比一致
if (e.detail.width > 375 * byclear) ctx.scale(375 * byclear / e.detail.width, 375 * byclear / e.detail.width);
ctx.drawImage(res.tempFilePaths[0], 0, 0, e.detail.width, e.detail.height)
ctx.draw()
// 后续操作
上面我们已经完整的将图片绘制到canvas中了,还不够,下面我们将设置设置canvas宽高大小,已达到完全展示
<canvas canvas-id="canvasIn" class="canvas" style="width:{{imgW}}rpx;height:{{imgH}}rpx;margin:0 auto;">
</canvas>
微信自适应单位是rpx,对于iphone 6 ,375px = 750rpx => 1px = 2rpx; 其他型号计算是带上比例byclear即可,然后图片小于屏幕宽度,不做处理,checkwh后续代码
this.setData({
imgW: e.detail.width > 375 ? 750 : e.detail.width * 2 / byclear,
imgH: e.detail.width > 375 ? 750 * whsrc : e.detail.height * 2 / byclear
canvas 缩放 zoom 方案
zoom方案对比scale方案,比较好的地方在于,不用计算canvas的大小,也不用缩放比例,直接将原图的宽高设置成canvas的宽高,然后,通过zoom对canvas进行缩放,直接放代码额,这里的缩放比例,即为 图片宽度 / 750,注意这里不需要比例计算,css样式会自动进行样式比率计算
关键wxml代码
<canvas canvas-id="canvasIn" class="canvas" style="width:{{imgW}}rpx;height:{{imgH}}rpx;margin:0 auto;zoom:{{imgW > 750 ? 750 / imgW : 1}}"></canvas>
关键js代码
var vhsrc = e.detail.height / e.detail.width
let res = this.data.res
let byclear = this.data.byclear
const ctx = wx.createCanvasContext('canvasIn', this);
ctx.drawImage(res.tempFilePaths[0], 0, 0, e.detail.width, e.detail.height)
ctx.draw()
this.setData({
imgW: e.detail.width * 2 / byclear,
imgH: e.detail.height * 2 / byclear