20
26

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 5 years have passed since last update.

canvasで画像の合成

Last updated at Posted at 2016-05-04

デモ:http://mo49.tokyo/qiita/20160504/

canvas.width, canvas.heightでcanvasのサイズ、
drawImage()で画像のサイズを決める。

デモでは風景、フレーム、文字の3枚を合成。

javascript
// 読み込みたい画像のパスの配列 後ろが上にくる
var fileAry = ['img/test1.png', 'img/test2.png', 'img/test3.png'];

var numFiles = fileAry.length;
var loadedCounter = 0;
var imgAry = [];

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

canvas.width = canvas.height = 500;

window.onload = function() {
	loadImgs();
};

function loadImgs(){

	var img = new Image();

	img.addEventListener('load', function(){
		loadedCounter++;
		imgAry.push(img);
		if(numFiles == loadedCounter){
			display(); // 画像をすべて読み込んだら描画
		} else {
			loadImgs();
		}
	}, false);
	
	img.src = fileAry[imgAry.length];
}

// 参照が残っているとガベージコレクトされないため、
// 明示的にImageオブジェクトを解放
function display(){
	for (var i in imgAry){
		ctx.drawImage(imgAry[i], 0, 0, canvas.width, canvas.height);
		imgAry[i] = null;
	}
}

参考
Canvasに画像を複数枚重ねて描画するには

20
26
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
20
26

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?