Mini programs such as WeChat and Alipay currently do not have interfaces for directly calling Image, but you can borrow the canvas curve to save the country, set an invisible canvas on the page, and then call the image through the interface capabilities of the canvas.
- WeChat case
wx.createSelectorQuery()
.select('#myCanvas') // 在 WXML 中填入的 id
.fields({
node: true, size: true })
.exec((res) => {
// Canvas 对象
const canvas = res[0].node
// 图片对象
const image = canvas.createImage()
// 图片加载完成回调
image.onload = () => {
// 将图片绘制到 canvas 上
console.log({
image, width: image.width, height: image.height});
}
image.src = 'https://open.weixin.qq.com/zh_CN/htmledition/res/assets/res-design-download/icon64_wx_logo.png'
})
- Alipay case
Page({
// 一定要在 canvas 的 onReady 中调用,否则获取到的 context 可能不正确
onCanvasReady() {
// 通过 SelectorQuery 获取 Canvas 实例
my.createSelectorQuery().select('#canvas').node().exec((res) => {
const canvas = res[0].node;
// const ctx = canvas.getContext('2d');
// console.log('canvas 宽高', canvas.width, canvas.height)
// // 开始绘画
// ctx.fillRect(0, 0, 50, 50);
const image = canvas.createImage();
image .src = "https://img.alicdn.com/tfs/TB1GvVMj2BNTKJjy0FdXXcPpVXa-520-280.jpg";
image .onload = function() {
console.log({
image, width: image.width, height: image.height});
}
image.onerror = function(err) {
console.log('load image err');
}
});
},
});