tips
:接下去會在github寫博客,簡書不再更新和修改文章,歡迎大家逛逛我的新博客點擊查看 ,我會盡量用更容易理解的方式寫好每一篇博客,大家一起學(xué)習(xí)交流??。
繼上一次的圖片懶加載波丰,這次講下js實現(xiàn)圖片預(yù)加載。
先上demo
再上代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script>
(function () {
function loadImages(sources, callback) {
var count = 0,
images = {},
imgNum = 0;
for (src in sources) {
imgNum++; //imgNum =2
}
for (src in sources) { //src 為 img1和img2
images[src] = new Image(); //images = {img1:img,img2:img}
images[src].onload = function () { //onload 事件會在頁面或圖像加載完成后立即發(fā)生
if (++count >= imgNum) { //當(dāng)次數(shù)大于等于2次時
callback(images); //調(diào)用loadImages的回調(diào)函數(shù)
}
}
images[src].src = sources[src]; //img1-> img.src = "http://pic.58pic.com/58pic/17/18/97/01U58PIC4Xr_1024.jpg";img2同理
}
}
//存儲圖片鏈接信息的關(guān)聯(lián)數(shù)組
var sources = { //想要多少張就放多少張
img1: "http://pic.58pic.com/58pic/17/18/97/01U58PIC4Xr_1024.jpg",
img2: "http://ww4.sinaimg.cn/large/006y8mN6gw1fa5obmqrmvj305k05k3yh.jpg",
img3:"http://ww1.sinaimg.cn/large/006y8mN6gw1fa7kaed2hpj30sg0l9q54.jpg"
};
//調(diào)用圖片預(yù)加載函數(shù)舶得,實現(xiàn)回調(diào)函數(shù)
loadImages(sources, function (images) {
//TO-DO something (如下面用canvas把圖畫出來)
//var images = new Image(); 創(chuàng)建一個<img>元素
// images.src = 'myImage.png'; 設(shè)置圖片源地址
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
//ctx.drawImage(image, dx, dy, dWidth, dHeight);
ctx.drawImage(images.img1, 20, 20, 100, 100);
ctx.drawImage(images.img2, 140, 20, 100, 100);
ctx.drawImage(images.img3, 260, 20, 100, 100);
});
}());
</script>
</head>
<body>
<canvas id="canvas" width="1000px" height="1000px"></canvas>
</body>
</html>
可以看出代碼注釋很詳細掰烟,
如果有些知識點還不是很清楚,請看我找的一些好的知識講解文章,省得像我一樣到處找啦沐批;
同時纫骑,如果您覺得有點幫助,可以關(guān)注給我的github項目給個start,watch哦,我會不定期更新js的一些開發(fā)常用的知識點技能衬横。
js開發(fā)常見技能收集->github
onload
for in 遍歷
Image 元素構(gòu)造器
為何使用++count
如何使用canvas創(chuàng)建圖片
canvas的drawImage()
如有錯誤,懇請指出指導(dǎo)^ ^