Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel is required to process package imports. If you need a different preprocessor remove all packages first.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

HTML

            
              <!-- three.min.js r87 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/87/three.min.js"></script>

<!-- OBJLoader.js -->
<script src="https://cdn.jsdelivr.net/gh/mrdoob/three.js@r87/examples/js/loaders/OBJLoader.js"></script>

<script src="//code.createjs.com/easeljs-0.8.0.min.js"></script>
<canvas id="myCanvas" width="465" height="150"></canvas>
            
          
!

CSS

            
              * {
  margin: 0;
  padding: 0;
  border: 0;
  overflow: hidden;
}

body {
  background: #ffffff;
}
            
          
!

JS

            
              // forked from siouxcitizen's "Three.js r70(WebGL使用) 3Dモデルにマウスクリックイベントを追加" http://jsdo.it/siouxcitizen/rrPcp
//3Dモデルのマウスクリックイベントを追加その2
//
//前回のコードから、
//勇者3Dモデル以外の3Dモデルについてもマウスクリックイベントを追加してみました
//3Dモデルごとのイベントの振り分けを、動けばいいや方式でテキトーに実装したので
//そのへん怪しいかもしれません
//
//操作方法:
//青ボタンで勇者キャラ左まわりにカメラが移動
//赤ボタンで勇者キャラ右まわりにカメラが移動
//黄色ボタンでカメラの距離を変更
//緑ボタンでカメラの高さを変更
//紫ボタンでカメラを元の位置へ移動
//勇者3Dモデル、村長3Dモデル、マップ(マップ用Plane)、をクリックでメッセージが表示されます
//
//
//
//引き続き以下のコード・サイトを参考にさせていただきました
//
//Three.js でピッキング(3Dモデルをマウスで選択)してみた
//http://tmlife.net/programming/javascript/threejs-picking.html
//
//Three.js 3Dモデルをマウスでクリック(ピッキング処理)
//http://gupuru.hatenablog.jp/entry/2013/12/02/190413
//
//多彩な表現力のWebGLを扱いやすくする「Three.js」 (5/5)
//http://www.atmarkit.co.jp/ait/articles/1210/04/news142_5.html
//
//JavaScript 3DレンダリングエンジンのThree.jsを試す
//http://kray.jp/blog/three-js/
//
//公式サイト?のサンプルも参考にしました
//view-source:http://threejs.org/examples/webgl_interactive_cubes.html
//
var container;
var scene; 
var camera; 
var renderer;
 
var isMouseDown = false;

//読み込みリソースURL
//フィールドマップ用テクスチャ画像URL
//var planeFieldPngURL = "http://jsrun.it/assets/d/c/u/e/dcue2.png";
//var planeDesertPngURL = "http://jsrun.it/assets/s/t/h/2/sth2z.png";
//var planeWaterPngURL = "http://jsrun.it/assets/5/z/t/g/5ztgk.png";
var planeFieldPngURL = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAdUlEQVR4nGMo/Cz9fyAxw6gD0AWsJzOAMbUtwmUu1hCgtiPwmYfXAdRwBCGzcKYBaocA0WmA3njUAaMOGHUA2Q5AztuUlBkUOYAaJSZZDoBZiGw5uY4YulFALTzqgFEHjDpgcDbJBrxROqDN8kHRMaEnHnUAADjp2hzJ3BYuAAAAAElFTkSuQmCC";
var planeDesertPngURL = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAUklEQVR4nGP4v1r3/0BihlEHjDpg1AH4JN/3M4AxuYYTo3/wO4DSIKbIAQOeBkYdMOqAUQeMOmDUAQNeFwz52hDmAHzmDO40MOqAUQeMOoAeGAArslGyN38s2wAAAABJRU5ErkJggg==";
var planeWaterPngURL = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAACTklEQVR4nK2X3VHDMBCEDQRCgBkqYRJIQuCJMiiCRiiFFqgqSgUmZ1ixWt/JDuHhxpaseD+d7sdpbp53rdnHZ5sNc2a3L21nfO9ZM992dvfa5ivMxnj32/u3YdywOO4jgAgC4grBY7NOcD82AEA1vHOQMYBntmb2mHrCkbE3IA5PZA/YwO7ZPTUAs9PFtuoR3OtxAKIbq7iKeOKAnDykUUfCEL2jgitswBCeJ7xAqgHgzCOg7h4vMwFAeAAsrmsikRzp8/5RZQgIQ5zvIaYZgucXq5QFPBAO8BCABT0A9gR7SqM6EsbzKsBQ2gFEj2qyTDm/2QPqjcgDnUW7x5jPXJ+f3W9zWnm75iroeaoAsCuXXN49uxzzV5tdFtHiwuu1FKtnGt6dll4NTAaYrlOxS96hl/NcPwqveK5lD0QAUXXTXqAwgMjrvUqncxw8Nr5cJ1cgqnYMyfGR64BXfhmEAa6fdu3Jot50huaqANVmtBe3+u9Vt7EtWY+u0d1z8VGA82UqIrkGoJBhu0ZgQRxppQCTH3GOZAXA1esBHCcFFItzDuMls81vwVEP1ZqQlmA+CszlLyItsewF3pECRgBeu+bnBQDELbrtxdNVKtLGK638zGtCvQ/PoFl17/VSRHdTy2utbOwlrzExQO6GvLuoium8upo7JtZ43wp6nE2RkwISVTmvvHo5jljyIPPvOTC8/I4CyPu4iDYTQRZHMCQwtvJ5FdBrVCFAzcbsWtdFYHnuEADvBUMAuq73m7+K145s6M9JAfHfAIc+PxrgWMAvxUC/XyZ/924AAAAASUVORK5CYII=";


//マップ配列 0:草原 1:砂漠 2:水辺
//マップ配列はマップの縦横の長さが一定(10*10)になるように設定
var mapData = [[ 1, 2, 1, 1, 1, 1, 0, 0, 2, 2],
               [ 1, 2, 1, 1, 1, 1, 1, 1, 0, 2],
               [ 1, 2, 1, 1, 1, 1, 1, 1, 1, 1],
               [ 1, 2, 1, 1, 1, 0, 0, 0, 0, 0],
               [ 2, 2, 1, 1, 1, 0, 0, 1, 1, 1],
               [ 2, 1, 1, 1, 0, 0, 0, 1, 0, 1],
               [ 2, 1, 1, 1, 0, 0, 0, 0, 1, 1],
               [ 2, 1, 1, 1, 1, 1, 0, 1, 0, 1],
               [ 2, 1, 1, 0, 1, 1, 0, 1, 0, 0],
               [ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]];

//3Dモデル共用テクスチャ
var texture;
//3Dモデル保持用
var yuushaModel;
var sonchoModel;

var projector = new THREE.Projector();
//オブジェクト格納グローバル変数
var targetList = []; 
//マウスのグローバル変数
var mouse = { x: 0, y: 0 };  

var rot = 0; // 角度
// マウスを押した状態かどうかを判別するフラグ
var isMouseDown = false;
// 一時的なマウスの値を格納する変数
var oldX = 0;
var targetRot = 0;

var cameraDistance = 4;

//CreateJS(EaselJS)用
var easelJSStage;
var easelJSMainMessage;

init();
render();

function init() {


    container = document.createElement( 'div' );
    document.body.appendChild( container );

    // 3Dシーン作成
    scene = new THREE.Scene(); 
    
    // カメラ設定
    camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 ); 
    //camera.position.x = 4.5;

    //勇者3Dモデル作成時の勇者座標
    //yuushaModel.position.set( 5, 0, -2 );
    //と
    //レンダリング時のカメラのX軸とY軸の座標位置の計算
    //camera.position.x = yuushaModel.position.x + cameraDistance * Math.sin(rot * Math.PI / 180);
    //camera.position.z = yuushaModel.position.z + cameraDistance * Math.cos(rot * Math.PI / 180);
    //よりカメラのX軸とZ軸の座標初期値を計算

    camera.position.x = 5 + cameraDistance * Math.sin(rot * Math.PI / 180);
    camera.position.y = 1; 
    //camera.position.z = 5.5; 
    
    camera.position.z = -2 + cameraDistance * Math.cos(rot * Math.PI / 180);

    // 3D描画用レンダラ設定
    renderer = new THREE.WebGLRenderer(); 
    //renderer.setSize( window.innerWidth, window.innerHeight ); 
    renderer.setSize( window.innerWidth, 315 ); 
    document.body.appendChild( renderer.domElement ); 
    // 背景を水色にする
    renderer.setClearColor(0x00ffff, 1); 

    // 光源の設定
    var light = new THREE.DirectionalLight("#ffffff", 1);
    var ambient = new THREE.AmbientLight("#771111");
    light.position.set(0, 100, 30);
    scene.add(light);
    scene.add(ambient);


    // PLANEオブジェクト作成
    // 共通PLANEジオメトリ作成
    var geometry = new THREE.PlaneGeometry( 1, 1, 1 ); 

    // 草原テクスチャの作成
    var fieldTexture = THREE.ImageUtils.loadTexture( planeFieldPngURL );
    var fieldMaterial = new THREE.MeshBasicMaterial( { map: fieldTexture, side: THREE.DoubleSide } );

    // 砂漠テクスチャの作成
    var desertTexture = THREE.ImageUtils.loadTexture( planeDesertPngURL );
    var desertMaterial = new THREE.MeshBasicMaterial( { map: desertTexture, side: THREE.DoubleSide } );

    // 水辺テクスチャの作成
    var waterTexture = THREE.ImageUtils.loadTexture( planeWaterPngURL );
    var waterMaterial = new THREE.MeshBasicMaterial( { map: waterTexture, side: THREE.DoubleSide } );

    // マップ配列を読み取り、Planeにマップ用テクスチャ画像を貼り付けて表示
    for (var xCounter = 0; xCounter < mapData.length; xCounter++) {

        for (var zCounter = 0; zCounter < mapData[0].length; zCounter++) {

            if(mapData[xCounter][zCounter] == 0) {
	            
	            var fieldPlane = new THREE.Mesh( geometry, fieldMaterial ); 
	            fieldPlane.position.x = xCounter;
	            fieldPlane.position.z = -zCounter;
	            fieldPlane.rotation.x =  Math.PI / 360 * 180;
	            fieldPlane.name = "座標X:" + xCounter + " Z:-" + zCounter + "草原マップ";
	            scene.add( fieldPlane ); 

            } else if (mapData[xCounter][zCounter] == 1) {

	            var desertPlane = new THREE.Mesh( geometry, desertMaterial ); 
	            desertPlane.position.x = xCounter;
	            desertPlane.position.z = -zCounter;
	            desertPlane.rotation.x = Math.PI / 360 * 180;
	            desertPlane.name = "座標X:" + xCounter + " Z:-" + zCounter + "砂漠マップ";
	            scene.add( desertPlane ); 

            } else if (mapData[xCounter][zCounter] == 2) {

	            var waterPlane = new THREE.Mesh( geometry, waterMaterial ); 
	            waterPlane.position.x = xCounter;
	            waterPlane.position.z = -zCounter;
	            waterPlane.rotation.x =  Math.PI / 360 * 180;
	            waterPlane.name = "座標X:" + xCounter + " Z:-" + zCounter + "水辺マップ";
	            scene.add( waterPlane.clone() ); 

            }

        }
    }

    // 3Dモデル用テクスチャ画像の読込
    texture = new THREE.Texture();
    var manager = new THREE.LoadingManager();
    manager.onProgress = function ( item, loaded, total ) {};
    var onProgress = function ( xhr ) {};
    var onError = function ( xhr ) {};

    var imageLoader = new THREE.ImageLoader( manager );
    //imageLoader.load( 'http://jsrun.it/assets/9/9/W/G/99WGE.png', function ( image ) {
    //imageLoader.load( '/assets/9/9/W/G/99WGE.png', function ( image ) {
    imageLoader.load( 'https://cdn.jsdelivr.net/gh/siouxcitizen/3DModel@master/yuusha.png', function ( image ) {

        texture.image = image;
        texture.needsUpdate = true;

    } );

    // 3Dモデル読込
    var objLoader = new THREE.OBJLoader( manager );

    var callbackYuushaModel = function ( object ) { createObj( object, -1 ); };
    var callbackSonchoModel = function ( object ) { createObj( object, 1 ); };

    //objLoader.load( '/assets/g/U/i/X/gUiXN', callbackYuushaModel); 
    //objLoader.load( '/assets/x/I/9/L/xI9L8', callbackSonchoModel); 
    objLoader.load( 'https://cdn.jsdelivr.net/gh/siouxcitizen/3DModel@master/yuusha.obj', callbackYuushaModel); 
    objLoader.load( 'https://rawcdn.githack.com/siouxcitizen/3DModel/03a4883f336e9a0e80bbcf52b9cf5a3777d16e31/obj/soncho.obj', callbackSonchoModel); 

    //document.addEventListener("mousedown", onMouseDown);
    //document.addEventListener("touchstart", onMouseDown);
    //document.addEventListener("mouseup", onMouseUp);
    //document.addEventListener("touchend", onMouseUp);
    //document.addEventListener("mousemove", onMouseMove);
    //document.addEventListener("touchmove", onMouseMove);

    //CreateJS(EaselJS)用ステージを作成
    var canvas = document.getElementById("myCanvas");
    easelJSStage = new createjs.Stage(canvas).set({x:canvas.width / 2, y:canvas.height / 2});

    initCreateJSParts();


    //3Dモデル勇者クリック時処理
    window.onmousedown = function (ev){

    if (ev.target == renderer.domElement) { 

        //マウス座標2D変換
        var rect = ev.target.getBoundingClientRect();    
        mouse.x =  ev.clientX - rect.left;
        mouse.y =  ev.clientY - rect.top;

        //マウス座標3D変換 width(横)やheight(縦)は画面サイズ
        mouse.x =  (mouse.x / 465) * 2 - 1;           
        mouse.y = -(mouse.y / 300) * 2 + 1;

        // マウスベクトル
        var vector = new THREE.Vector3( mouse.x, mouse.y ,1);

        // vector はスクリーン座標系なので, オブジェクトの座標系に変換
        projector.unprojectVector( vector, camera );

        // 始点, 向きベクトルを渡してレイを作成
        var ray = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() );

        // 勇者3Dモデルクリック判定
        var intersects = ray.intersectObjects( yuushaModel.children );
        // 勇者3Dモデルクリック時にメッセージ表示  
        if ( intersects.length > 0 ){
            easelJSMainMessage.text = "はじめまして勇者です!";
            return;
        } 
 
        // 村長3Dモデルクリック判定
        intersects = ray.intersectObjects( sonchoModel.children );
        // 村長3Dモデルクリック時にメッセージ表示  
        if ( intersects.length > 0 ){                       
            easelJSMainMessage.text = "はじめまして村長です!";
            return;
        } 

        // マップPlaneクリック判定
        intersects = ray.intersectObjects( scene.children );
        // マップPlaneクリック時にメッセージ表示  
        if ( intersects.length > 0 ){                       
            easelJSMainMessage.text = intersects[0].object.name + "がクリックされました";
            return;
        } 

    }
    };

}

// 3Dモデル読込時コールバック関数
function createObj( object, x ) {

    object.traverse( function ( child ) {

        if ( child instanceof THREE.Mesh ) {

            child.material.map = texture;
            child.material.wireframe = false;
        }

        } );

        object.scale.set( 1.5, 1.5, 1.5 );

        //勇者3Dモデルを作成・設置
        if(x == -1) {
            object.scale.set( 0.1, 0.1, 0.1 );
            yuushaModel = object;
            yuushaModel.position.set( 5, 0, -2 );
            yuushaModel.rotation.y =Math.PI;
            scene.add( yuushaModel );

        //村長3Dモデルを作成・設置
        } else if (x == 1) {
            object.scale.set( 0.1, 0.1, 0.1 );
            sonchoModel = object;
            sonchoModel.position.set( 5, 0, -5 );
            scene.add( sonchoModel );

        }

}

function render() { 

    requestAnimationFrame( render ); 

    //rot += 0.5; // 毎フレーム角度を0.5度ずつ足していく
    // イージングの公式を用いて滑らかにする
    // 値 += (目標値 - 現在の値) * 減速値
    rot += (targetRot - rot) * 0.05;

    // 角度に応じてカメラの位置を設定
    camera.position.x = yuushaModel.position.x + cameraDistance * Math.sin(rot * Math.PI / 180);
    camera.position.z = yuushaModel.position.z + cameraDistance * Math.cos(rot * Math.PI / 180);
    // キャラクタ方向を見つめる
    camera.lookAt({x:yuushaModel.position.x,  y:yuushaModel.position.y,  z:yuushaModel.position.z});

    renderer.render(scene, camera);
    
    easelJSStage.update();
}

// マウスを押したとき
function onMouseDown(event) {
    isMouseDown = true;
    oldX = event.pageX;
}

// マウスを動かした時
function onMouseMove(event) {
    if (isMouseDown) {
        // 3DモデルをX軸とY軸方向に回転させます
        var dy = event.pageX - oldX;
        targetRot += dy * 0.25;
        oldX = event.pageX;
    }
}

// マウスを離したとき
function onMouseUp(event) {
    isMouseDown = false;
}

//CreateJS(EaselJS)関連オブジェクト初期化
function initCreateJSParts() {

    //メッセージ作成・表示
    easelJSMainMessage = new createjs.Text("EaselJSでつくるAway3Dインターフェース", "20px Arial", "#000000");
    easelJSMainMessage.x = -200;
    easelJSMainMessage.y = 5;
    easelJSStage.addChild(easelJSMainMessage);

    //青ボタン作成
    var blueBtn = new createjs.Shape(); 
    easelJSStage.addChild(blueBtn);
    blueBtn.addEventListener("click", function(){ 
                                          targetRot = targetRot - 60; 
                                          easelJSMainMessage.text = "青ボタン押下 カメラ位置回転移動";
                                      }
                            );

    var myGraphics = blueBtn.graphics;
    var fillCommand = myGraphics.beginFill("blue").command;
    var circleCommand = myGraphics.drawCircle(0, 0, 25).command;
    blueBtn.x = -180;
    blueBtn.y = -35;

    //赤ボタン作成
    var redBtn = new createjs.Shape(); 
    easelJSStage.addChild(redBtn);
    redBtn.addEventListener("click", function(){ 
                                          targetRot = targetRot + 60; 
                                          easelJSMainMessage.text = "赤ボタン押下 カメラ位置回転移動";
                                      }
                            );

    myGraphics = redBtn.graphics;
    fillCommand = myGraphics.beginFill("red").command;
    circleCommand = myGraphics.drawCircle(0, 0, 25).command;
    redBtn.x = -100;
    redBtn.y = -35;

    //黄色ボタン作成
    var yellowBtn = new createjs.Shape(); 
    easelJSStage.addChild(yellowBtn);
    yellowBtn.addEventListener("click", function(){ 
                                             cameraDistance = cameraDistance - 1;
                                             if (cameraDistance < 2){
                                                 cameraDistance = 6;
                                             } 
                                             easelJSMainMessage.text = "黄色ボタン押下 カメラ距離移動";
                                         }
                               );

    myGraphics = yellowBtn.graphics;
    fillCommand = myGraphics.beginFill("yellow").command;
    circleCommand = myGraphics.drawCircle(0, 0, 25).command;
    yellowBtn.x = -20;
    yellowBtn.y = -35;

    //緑ボタン作成
    var greenBtn = new createjs.Shape(); 
    easelJSStage.addChild(greenBtn);
    greenBtn.addEventListener("click", function(){ 
                                             camera.position.y = camera.position.y + 0.5;
                                             if (camera.position.y > 4) {
                                                 camera.position.y = 0.5;
                                             }
                                             easelJSMainMessage.text = "緑ボタン押下 カメラ高さ変更";
                                         }
                               );

    myGraphics = greenBtn.graphics;
    fillCommand = myGraphics.beginFill("green").command;
    circleCommand = myGraphics.drawCircle(0, 0, 25).command;
    greenBtn.x = 60;
    greenBtn.y = -35;

    //紫ボタン作成
    var purpleBtn = new createjs.Shape(); 
    easelJSStage.addChild(purpleBtn);
    purpleBtn.addEventListener("click", function(){ 
                                             targetRot = 0;
                                             camera.position.y = 1;
                                             cameraDistance = 4; 
                                             easelJSMainMessage.text = "紫ボタン押下 カメラ初期位置";
                                         }
                               );

    myGraphics = purpleBtn.graphics;
    fillCommand = myGraphics.beginFill("purple").command;
    circleCommand = myGraphics.drawCircle(0, 0, 25).command;
    purpleBtn.x = 140;
    purpleBtn.y = -35;

    easelJSStage.update();
}

//function getMouseX(event) {
//    if (event.type.indexOf("touch") == -1)
//        return event.clientX;
//    else
//        return event.touches[0].clientX;
//}

//function getMouseY(event) {
//    if (event.type.indexOf("touch") == -1)
//        return event.clientY;
//    else
//        return event.touches[0].clientY;
//}
            
          
!
999px

Console