想做一个从相册取得照片,先用OffScreenCanvas裁剪,通过wx.canvasToTempFilePath拿到裁剪后图片地址,然后再显示到wxxl中的<image>的功能,
在社区查询说要在image.onload方法中执行wx.canvasToTempFilePath才能拿到地址,但是我的image.onload方法不执行,是什么原因?
通过以下代码创建了Image对象
const image = this.data.offscreenCanvas.createImage()
然后给通过以下代码给image传入从相册拿到的图片地址,为什么image.onload不执行呢?
image.onLoad = () => {
console.log("image.onLoad 为什么不执行?")
}
image.src = imageUrl
-------- 以下是完整代码 ------------
Page({
/**
* 页面的初始数据
*/
data: {
imagePath: '',
clipedImagePath: '',
offscreenCanvas: null,
renderingContext: null,
canvasWidth: 0,
canvasHeight: 0,
canvasHWRatio: 0.0,
},
onLoad(){
this.data.canvasHWRatio = 1.427
var windowWidth = wx.getSystemInfoSync().windowWidth
var pixelRatio = wx.getSystemInfoSync().pixelRatio
this.data.canvasWidth = windowWidth * pixelRatio
this.data.canvasHeight = Math.ceil(this.data.canvasWidth * this.data.canvasHWRatio)
this.initCanvas()
},
/* 从相册选择照片 */
tapChoose(){
const that = this
wx.chooseMedia({
count: 1,
mediaType: ['image'],
sourceType: ['album'],
maxDuration: 30,
camera: 'back',
success(res) {
console.log("tempFiles = ")
console.log(res.tempFiles)
that.setData({
imagePath: res.tempFiles[0].tempFilePath
})
that.getClipedImagePath(res.tempFiles[0].tempFilePath)
}
})
},
/* 初始化 OffscreenCanvas */
initCanvas(){
// 创建离屏 2D canvas 实例
const offscreenCanvas = wx.createOffscreenCanvas({type: '2d', width: this.data.canvasWidth, height: this.data.canvasHeight})
// 获取 context。注意这里必须要与创建时的 type 一致
const renderingContext = offscreenCanvas.getContext('2d')
this.data.offscreenCanvas = offscreenCanvas
this.data.renderingContext = renderingContext
},
getClipedImagePath(imageUrl){
console.log("getClipedImagePath 执行")
// 创建一个图片
const image = this.data.offscreenCanvas.createImage()
// 等待图片加载
image.onLoad = () => {
console.log("image.onLoad 为什么不执行?")
}
image.src = imageUrl
}
})
应该是image.onload ,不是 image.onLoad ,注意大小写问题,已经在这个帖子解决了
https://developers.weixin.qq.com/community/develop/doc/0006ec4208894875cb6ff22275c000?jumpto=comment&commentid=00060692d38780f3d76f17e2a5bc