Tech Tips

  1. Uncategorized
  2. 133 view

[Javascript][Three.js]mouse move

I make html file which is previous three.js article’s index.html load new main.js which is below.
window.onload = function() {
        // Canvas size
        var width = 640;
        var height = 480;

        // Cube Size
        var geometry = new THREE.CubeGeometry(100, 100, 100);
        // Cube Material Info(not metal)
        var texture = new THREE.ImageUtils.loadTexture('./img/tex.jpg');
        var material = new THREE.MeshLambertMaterial({map: texture});
        // Create Cube
        var mesh = new THREE.Mesh(geometry, material);
        // Rotate Cube
        mesh.rotation = {x: 0.5, y: 0.5, z: 0.0};

        // Setting Camera
        var camera = new THREE.PerspectiveCamera(40, width / height, 1, 1000);
        // Camera Position
        camera.position.z = -400;
        // Camera Angle
        camera.lookAt(mesh.position);

        // Create Space
        var scene = new THREE.Scene();
        // Add cube to Space
        scene.add(mesh);

        // Create Light element
        var light    = new THREE.DirectionalLight(0xffffff, 1.5);
        // Light element position
        light.position = {x: 0, y: 0.2, z: -1};
        // Add light element to the space
        scene.add(light);

        // Create renderer
        var renderer = new THREE.WebGLRenderer();
        // Set canvas size
        renderer.setSize(width, height);

        // Set canvas to div element
        document.getElementById('canvas').appendChild(renderer.domElement);

        var mousedown = false;
        renderer.domElement.addEventListener('mousedown', function(e) {
                mousedown = true;
                prevPosition = {x: e.pageX, y: e.pageY};
        }, false);

        renderer.domElement.addEventListener('mousemove', function(e) {
                if (!mousedown) return;
                moveDistance = {x: prevPosition.x - e.pageX, y: prevPosition.y - e.pageY};
                mesh.rotation.x += moveDistance.y * 0.01;
                mesh.rotation.y -= moveDistance.x * 0.01;

                prevPosition = {x: e.pageX, y: e.pageY};
                render();
        }, false);

        renderer.domElement.addEventListener('mouseup', function(e) {
                mousedown = false;
        }, false);

        function render(){
                renderer.render(scene, camera);
        }
}
Result is below.
It’s interesting. Please try drag. The cube will rotate. I’ll make something with it in the future.
Demo

Uncategorized recent post

  1. Run Amazon FreeRTOS on M5Stack Core2 for AWS …

  2. Udacity Self-Driving Car Engineer Nanodegree …

  3. Install sbt 1.0.0 and run sample template

  4. Visualization of Neural Network and its Train…

  5. [Machine Learning]Created docker image includ…

関連記事

PAGE TOP