During development, if you need to use canvas to draw multiple pictures at the same time, but because the sizes of the pictures are different, the picture at the front of the array may not be loaded first and then drawn, which may cause the order of the drawn pictures to be arranged. It is different from what I expected (especially because it is particularly obvious for images with domain name redirection added across domains). My solution is to draw them all first, sort them, and then append them to the required nodes.
<div id=myContent></div>let imgArray = ['img1.png', 'img2.png'];let receiveArray = new Array();let $myContent = document.getELmentById(myContent);let {imgW, imgH} = {300, 300};let Canvas = document.createElement('canvas');let ctx = Canvas.getContext(2d);let scaleBy = 2;Canvas.width = imgW * scaleBy;Canvas.height= imgH * scaleBy;imgArray.forEach((e, idx) => { let img = new Image(); img. src = e; e.addEventListener('load', () => { ctx.drawImage(img, 0, 0, imgW * scaleBy, imgH * scaleBy); let imgCont = new Image(); imgCont.src = Canvas.toDataURL(); imgCont.id = 'img' + idx; receiveArray.push(imgCont); // The img that will be drawn Nodes are collected into an array. The order here may be different from the order of imgArray if (receiveArray.length === imgArray.length) { //All pictures are loaded and drawn let sortArr = new Array(); receiveArray.forEach(ex => { //Sort all drawn pictures in imgArray order sortArr[ex.id.split('img')[1]] = ex; }) sortArr.forEach(ex2 => { $myContent.appendChild(ex2) }) } })})In fact, this is also a somewhat helpless approach, because it is impossible to determine the actual size of the loaded images. Small images will be loaded and drawn first. If the domain name is redirected, this phenomenon will be amplified. Therefore, the method of sorting after drawing is adopted. If anyone thinks of a better way, please correct and criticize.
The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope everyone will support VeVb Wulin Network.