Back to Demos

This demo shows how you make a widget with a tool.

Clara.io demo resources:

Visit Base Scene


var sceneId = 'b0929e31-cded-496e-9649-bd08a2e5f6e5';
var api = claraplayer('player');

api.on('threeinitialized', function() {
  var THREE = api.player.getThree().THREE;

  api.commands.addCommand({
    enabled: true,
    active: true,
    widget: {
      draw: function(manipObject) {
        var cone = new THREE.ConeGeometry(0.2, 0.6, 25);
        var rotateGeometry = new THREE.TorusGeometry(1.5, 0.05, 16, 100, 2.5);
        cone.rotateX(Math.PI);
        cone.translate(1.45, 0, 0);
        rotateGeometry.merge(cone);

        var clone = rotateGeometry.clone();
        clone.rotateZ(Math.PI);
        rotateGeometry.merge(clone);

        var greenMaterial = new THREE.MeshBasicMaterial({ color: 0x00ff00, transparent: true, opacity: 0 });
        var rotateSymbol = new THREE.Mesh(rotateGeometry, greenMaterial);
        rotateSymbol.position.set(0, 0.1, 0);
        rotateSymbol.rotateX(Math.PI / 2);
        manipObject.add(rotateSymbol);
      },
      position: function (manipObject) {
        var selectedItem = api.selection.lastSelectedNode();
        if (!selectedItem) {
          manipObject.children[0].material.opacity = 0;
          return;
        }
        manipObject.children[0].material.opacity = 1;
        var selectedPosition = new THREE.Vector3().setFromMatrixPosition(
          api.scene.getWorldTransform(selectedItem)
        );
        manipObject.position.copy(selectedPosition);
      },
    },
    tool: {
      drag: function (ev) {
        var bb = ev.rect;
        var selectedItem = api.selection.lastSelectedNode();
        if (!selectedItem) return;

        return {
          momentum: false,
          handle: function (ev) {
            var degrees = 360 * ev.deltaX / bb.width;
            var rotation = api.scene.get({ id: selectedItem, plug: 'Transform', operatorIndex: 0, property: 'rotation' });
            api.scene.set({ id: selectedItem, plug: 'Transform', property: 'rotation' },
              { x: rotation.x, y: rotation.y + degrees, z: rotation.z });
          }
        }
      }
    }
  }, 'planeRotate');
});

api.sceneIO.fetchAndUse(sceneId).then(function() {
  ['orbit', 'pan', 'zoom', 'vrMode', 'home', 'fullscreen'].map(function(tool) {return api.player.hideTool(tool)});
  api.commands.runCommand('planeRotate');

  document.getElementById('baseScene').setAttribute('href','https://clara.io/view/'+sceneId);
});