很简单的测试canvas , 本地选取一张图片,显示在画布上。开发工具、iOS真机正常,安卓真机测试不行,也无报错。安卓机微信8.0.32,基础库2.19.4,真机测试2.0,开发工具最新版。
每一步都执行,都能获取到图片信息,就是到了draw 时不显示。延时执行也不起作用。布局也极简单,一按钮,一图片,一画布。请问可能是什么原因?
<view class="container">
<button bindtap="chooseImage">aaaaa</button>
<image src="{{avatar}}" style="width: 300rpx;height: 300rpx;background-color: rgb(255, 127, 127);" mode="aspectFit"></image>
<canvas type="2d" id="canvas-avatar" style="width: 300rpx;height: 300rpx;background-color: aquamarine;"></canvas>
</view>
代码:
var myCanvas = null
Page({
data: {
avatar: ''
},
chooseImage() {
let that = this;
wx.chooseMedia({
count: 1,
mediaType: ['image'],
sourceType: ['album'],
sizeType: ['compressed'],
success(res) {
that.setData({ avatar: res.tempFiles[0].tempFilePath });
//延时
// setTimeout(()=>{
// that.drawCanvas()
// },2000)
that.drawCanvas()
}
})
},
//绘制
drawCanvas() {
let that = this
wx.createSelectorQuery().selectAll('#canvas-avatar').node(res => {
myCanvas = res[0].node
const ctx1 = myCanvas.getContext('2d')
myCanvas.width = 200
myCanvas.height = 200
// ctx1.scale(dpr,dpr)
let image = myCanvas.createImage();
let x = 0, y = 0, size_clip = 0;
image.src = that.data.avatar;
image.onload = function () {
if (image.naturalWidth || image.naturalHeight) {//有高宽
if (image.naturalWidth >= image.naturalHeight) {
x = (image.naturalWidth - image.naturalHeight) / 2
size_clip = image.naturalHeight
} else {
y = (image.naturalHeight - image.naturalWidth) / 2
size_clip = image.naturalWidth
}
console.log('wa', image.naturalWidth, 'ha', image.naturalHeight)
} else {//继续求width/height
wx.getImageInfo({
src: that.data.avatar,
success(res) {
if (res.width >= res.height) {
x = (res.width - res.height) / 2
size_clip = res.height
} else {
y = (res.height - res.width) / 2
size_clip = res.width
}
console.log('w', res.width, 'h', res.height)
}
})
}
ctx1.drawImage(image, x, y, size_clip, size_clip, 0, 0, myCanvas.width, myCanvas.height);
}
}).exec()
},
})
你好请问一下解决了吗,我这也有这个问题
这个是异步的,是否判断过size_clip在绘制的时候,还没有数据