如何将任意数量的图像加载到画布上

时间:2016-10-10 12:48:24

标签: javascript html5 html5-canvas

如何将任意数量的图像加载到画布上。这个数字可能是5,6 ......我怎么能这样做。到目前为止,我只能加载2个图像,但这个代码不能用于动态数量的图像。代码应该是这样的,它应该加载许多图像。

<!DOCTYPE HTML>
<html>
<head>
    <style>
        body {
            margin: 0px;
            padding: 0px;
        }
    </style>
</head>
<body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
    <script>
        function loadImages(sources, callback) {
            var images = {};
            var loadedImages = 0;
            var numImages = 0;
    // get num of sources
    for(var src in sources) {
        numImages++;
    }
    for(var src in sources) {
        images[src] = new Image();
        images[src].onload = function() {
            if(++loadedImages >= numImages) {
                callback(images);
            }
        };
        images[src].src = sources[src];
    }
}
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
//var availableTags = <?php  echo json_encode($img_arr1) ?>;

var sources = {
    darthVader: 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg',
    yoda: 'http://www.html5canvastutorials.com/demos/assets/yoda.jpg'

};

loadImages(sources, function(images) {
    context.drawImage(images.darthVader, 100, 30, 200, 137);
    context.drawImage(images.yoda, 350, 55, 93, 104);
});

</script>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

将相关数据保存为对象列表并循环显示:

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
//var availableTags = <?php  echo json_encode($img_arr1) ?>;
var sourceSets = [];
var sources = {};
//Draw function
function draw() {
	//Clear board
	context.clearRect(-10, -10, 4000, 4000);
	//Loop through images and draw each one
	for (var i = 0; i < sourceSets.length; i++) {
		context.drawImage(sourceSets[i].img, sourceSets[i].x, sourceSets[i].y, sourceSets[i].w, sourceSets[i].h);
	}
}

function loadSource(src, x, y, w, h) {
	//Setting defaults
	if (src === void 0) {
		src = '';
	}
	if (x === void 0) {
		x = 0;
	}
	if (y === void 0) {
		y = 0;
	}
	if (w === void 0) {
		w = 100;
	}
	if (h === void 0) {
		h = 100;
	}
	//Creating image and loading from src
	if(sources[src] === void 0) {
		sources[src] = new Image();
		sources[src].onload = function () {
			draw();
		};
		sources[src].src = src;
	}
	var img = sources[src];
	img.src = src;
	//Save all relevant data in an object
	sourceSets.push({
		src : src,
		x : x,
		y : y,
		w : w,
		h : h,
		img : img
	});
}
//Add whatever amount of images here
var amount = parseInt(prompt("amount",4));
for(var i = 0; i < amount; i++) {
	if(i%2 === 0) {
		loadSource('http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg', Math.random() * 400, Math.random() * 400, 200, 137);
	} else {
		loadSource('http://www.html5canvastutorials.com/demos/assets/yoda.jpg', Math.random() * 400, Math.random() * 400, 93, 104);
	}
}
<canvas id="myCanvas" width="600" height="540"></canvas>