19
17

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.

three.jsで画像を表示する最小サンプル

Last updated at Posted at 2017-06-03

three.jsを使ってただ画像を表示したいだけなのに、手間取ったのでメモです。three.jsのバージョンは85です。

まずサーバーをたてます。簡単な方法としては、コードのあるディレクトリで以下のコマンドを実行します。サーバーをたてた上でアクセスしないとエラーになります。(参考)

$ php -S localhost:9000

そして、以下の通りにコードを書いて、ブラウザでlocalhost:9000にアクセスします。

index.html
<html>
	<head>
		<meta charset=utf-8>
		<title>Algorithmic Visualization</title>
		<style>
			body { margin: 0; }
			canvas { width: 100%; height: 100% }
		</style>
	</head>
	<body>
		<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/85/three.min.js"></script>
		<script src="show_image.js"></script>
	</body>
</html>
show_image.js
// シーン
var scene = new THREE.Scene();

// レンダラー
var renderer = new THREE.WebGLRenderer({alpha:true, antialias: true });
renderer.setClearColor(0xffffff,1);
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setPixelRatio(window.devicePixelRatio ? window.devicePixelRatio : 1);
document.body.appendChild( renderer.domElement );

// カメラ
var camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 1, 1000 );
camera.position.set(0, 0, 10);

// ライト
var light = new THREE.AmbientLight( 0xffffff );
scene.add( light );

// 画像を読み込む
var texture = new THREE.TextureLoader().load('path/to/file.jpg',
(tex) => { // 読み込み完了時
    // 縦横比を保って適当にリサイズ
    const w = 5;
    const h = tex.image.height/(tex.image.width/w);

    // 平面
    const geometry = new THREE.PlaneGeometry(1, 1);
    const material = new THREE.MeshPhongMaterial( { map:texture } );
    const plane = new THREE.Mesh( geometry, material );
    plane.scale.set(w, h, 1);
    scene.add( plane );
});

// レンダリング
function render() {
    requestAnimationFrame(render);
    renderer.render(scene, camera);
}
render();
19
17
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
19
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?