0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

画像を並列に読み込む

Posted at

画像を同時に読み込むをする

qiita.js
var pathArray = ["*","*","*","*","*","*"];
var imgArray = [];
var counter = 0;
for(var i = 0 ; i < pathArray.length ; i++){
	var img = new Image();
	img.src = pathArray[i];
	imgArray.push(img);
	img.onload = function(){
		counter++;
		if(counter == pathArray.length){
			console.log("LOAD COMPLETE")
		}
	}
}

数個であればこれでもいいけど、実際に読み込みをする時に、N個並行で読み込むっていうのを作りたい。

qiita.js
function loadPararell(_pathArray,N,_func){
	var imgArray = [];
	var counter = 0;
	for(var i = 0 ; i < N ; i++){
		loadimg(i)
	}
	function loadimg(i){
		var img = new Image();
		img.src = _pathArray[i];
		imgArray.push(img);
		img.onload = function(){
			console.log("LOAD:"+img.src)
			counter++;
			if(counter == _pathArray.length){
				console.log("LOAD COMPLETE")
				_func(imgArray);
			}else if(counter < _pathArray.length - 2){
				loadimg(counter+2);
			}
		}
	}
}
var pathArray = ["assets/img/place_1.png","assets/img/place_2.png","assets/img/place_3.png","assets/img/place_4.png","assets/img/place_1.png"];;
loadPararell(pathArray,3,function(arr){
	console.log(arr);
});

できた。これでpathArrayで画像を読み込んだら、その画像のデータを配列に入れて完成で返してくれるものができた。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?