javascript promise all实现图片顺序加载
不使用promise时是异步加载,图片加载的顺序不固定
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<style>
* {
margin: 0;
padding: 0;
}
</style>
<title>demo</title>
</head>
<body>
<div id="image_div" style="height:800px;overflow:scroll;">
<table id="image_table">
</table>
</div>
</body>
</html>
<script>
let path_list = [
"00.JPG",
"01.JPG",
"02.JPG",
"03.JPG",
"04.JPG",
"05.JPG",
"06.JPG",
"07.JPG",
"08.JPG",
"09.JPG",
"10.JPG",
"11.JPG"
]
function loadImage(path, num) {
const newImg = document.createElement("img")
newImg.src = path
let canv1 = document.createElement('canvas')
canv1.width =480
canv1.height =320
newImg.onload = () => {
let ctx1 = canv1.getContext('2d')
ctx1.drawImage(newImg, 0, 0)
ctx1.font = "30px Arial"
ctx1.fillStyle = 'rgba(0,0,0)'
ctx1.fillText(num, 0, 315)
const newImg1 = document.createElement("img")
newImg1.src = ctx1.canvas.toDataURL('image/jpeg')
var tr=document.createElement("tr")
var xh=document.createElement("td")
var image2 = document.createElement('img')
image2.src = ctx1.canvas.toDataURL('image/jpeg')
xh.appendChild(image2)
tr.appendChild(xh)
var tab=document.getElementById("image_div")
tab.appendChild(tr)
}
}
for (let i = 0; i < path_list.length; i++) {
loadImage(path_list[i], i + 1)
}
</script>
使用promise all可以实现顺序加载
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<style>
* {
margin: 0;
padding: 0;
}
</style>
<title>demo</title>
</head>
<body>
<div id="image_div" style="height:800px;overflow:scroll;">
<table id="image_table">
</table>
</div>
</body>
</html>
<script>
let path_list = [
"00.JPG",
"01.JPG",
"02.JPG",
"03.JPG",
"04.JPG",
"05.JPG",
"06.JPG",
"07.JPG",
"08.JPG",
"09.JPG",
"10.JPG",
"11.JPG"
]
function loadImage(path, num) {
return new Promise(function (resolve, reject) {
const newImg = document.createElement("img")
newImg.src = path
let canv1 = document.createElement('canvas')
canv1.width = 480
canv1.height = 320
newImg.onload = () => {
let ctx1 = canv1.getContext('2d')
ctx1.drawImage(newImg, 0, 0)
ctx1.font = "30px Arial"
ctx1.fillStyle = 'rgba(0,0,0)'
ctx1.fillText(num, 0, 315)
const newImg1 = document.createElement("img")
newImg1.src = ctx1.canvas.toDataURL('image/jpeg')
resolve(newImg1)
}
newImg.onerror = () => {
reject("加载错误")
}
})
}
let arr = []
for (let i = 0;i < path_list.length; i++) {
arr.push(loadImage(path_list[i], i + 1))
}
Promise.all(arr).then((values)=>{
for (let v of values) {
var tr=document.createElement("tr")
var xh=document.createElement("td")
xh.appendChild(v)
tr.appendChild(xh)
var tab=document.getElementById("image_table")
tab.appendChild(tr)
}
})
</script>