我要使用Canvas动态写入多个图片和文本;图片要在Image的onLoad中调用drawImage方法才能写入到Canvas中,但是不同Image的OnLoad方法异步执行的,先执行的Image写在最下层,如何准确控制各个Image的上下关系?
主要JS如下:
var img = canvas.createImage();
img.src = '/images/hb5.png';
img.onload = () => {
// this._img = img;
console.log('img',img);
console.log('img.width',img.width);
console.log('img.height',img.height);
ctx.drawImage(img,0,0,this.getPx(750),this.getPx(1334));
}
var imgHead = canvas.createImage();
imgHead.src = 'https://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eqAE0ydqk97jiaicrjMEhhXDDpgXQkFHRTdaYNEPC222ibMd4lOzOuQaaPLSude6XUdl7G0peAZWhdzw/132';
imgHead.onload = () => {
// this._img = img;
console.log('imgHead',imgHead);
console.log('imgHead.width',imgHead.width);
console.log('imgHead.height',imgHead.height);
var scale = this.getScale(imgHead);
ctx.drawImage(imgHead,this.getPx(125),this.getPx(20),this.getPx(scale*imgHead.width),this.getPx(scale*imgHead.height));
}
ctx.setFontSize = "40";
// ctx.fillStyle = "rgba(0, 0, 0, 1)";
ctx.fillText("我是分享文字111111111", this.getPx(100), this.getPx(600));
ctx.fillStyle = "rgba(0, 0, 0, .5)";
ctx.fillText("我是分享文字222", this.getPx(100), this.getPx(700));
ctx.draw()
直接使用这种回调方式肯定是不行的,使用Promise+async await处理异步问题控制图片和绘制图片的顺序