📌

AR.jsでWebARしてみる(8-2) Canvas Texturesで画像ファイルを順番に表示する

2020/12/20に公開

はじめに

WebARで分かったことメモしていく
今回はAR.jsでWebARしてみる(8) Canvas Texturesのスクリプトを応用して、画像ファイル(.png)を1秒間隔で切り替えていくスクリプトを作成した。

デモ

ソース

<!doctype HTML>
<html>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
<script src="js/aframe.min.js"></script>
<script src="js/aframe-ar.js"></script>
<body style="margin: 0px; overflow: hidden;">
<script>
AFRAME.registerComponent('canvas-texture', {
	init: function()
	{
		this.canvas = document.querySelector("#myCanvas");
		this.canvas.width = 512;
		this.canvas.height = 512;
		this.context = this.canvas.getContext('2d');
		this.x = 200;
		this.y = 100;
		this.dx = 5;
		this.dy = 3;
		this.image = ["00.png","01.png","02.png","03.png","04.png","05.png","06.png","07.png","08.png","09.png"];
		this.imgSrc = "";
		this.glNo = 0;
		this.dtsum = 0;
    },
	update: function(){
		let material = this.el.getObject3D("mesh").material;
		const chara = new Image();
		chara.src = "images/" + this.image[ this.glNo ];
		chara.onload = () => {
			this.context.drawImage(chara, 0, 0);
			if (!material.map)
				return;
			else
				material.map.needsUpdate = true; 
		};
    },
	tick: function(t, dt)
	{
		this.dtsum += dt;
		if( this.dtsum >= 1000 ){
			this.dtsum = 0;
			if( this.glNo >= this.image.length-1 ){
				this.glNo = 0;
			}else{
				this.glNo += 1;
			}
			this.update();
		}        
	}
});
</script>

<a-scene embedded vr-mode-ui="enabled: false;" arjs="debugUIEnabled: false;">
    <a-assets>
        <canvas id="myCanvas"></canvas>
    </a-assets>
    <a-marker type="pattern" url="data/hiro.patt">
        <a-box
               position="0 0.5 0" 
               material="src: #myCanvas; transparent: true; opacity: 0.95;"
               canvas-texture>
        </a-box>
    </a-marker>
    <a-entity camera></a-entity>
</a-scene>
</body>
</html>

ちょっと説明

スクリプトの処理をちょっとだけ説明
this.imageに画像ファイルのファイル名を格納。

this.image = ["00.png","01.png","02.png","03.png","04.png","05.png","06.png","07.png","08.png","09.png"];

用意した画像

Discussion