A-Frame: how to animate objects on scene with scenario - animation

Let's speak about 3D movies or smth like that. Ok, I know how to animate properties with <a-animation>. I also tried aframe-animation-component based on animejs. I love animejs. It have useful anime.timeline(). You can just set frames of this and animate much objects as you want. But it have very serious trouble: it isn't able animate complex attributes like position or scale or another serialized component. This trouble I've described here. Animejs's timeline is perfect for DOM, but very hard to use with A-Frame.
I also found this example for three.js. May be I can generate same animation for my A-Frame scene? Looking for any suggestions about scene's keyframes or timelines.

https://www.npmjs.com/package/aframe-animation-timeline-component
I published the animation timeline component.
<a-scene animation-timeline__1="timeline: #myTimeline; loop: true">
<a-timeline id="myTimeline">
<a-timeline-animation select="#text1" name="togglevisible"></a-timeline-animation>
<a-timeline-animation select="#text1" name="fadein"></a-timeline-animation>
<a-timeline-animation select="#text1" name="fadeout"></a-timeline-animation>
<a-timeline-animation select="#text1" name="togglevisibleoff"></a-timeline-animation>
<a-timeline-group>
<a-timeline-animation select="a-entity[mixin~=box]" name="fadein"></a-timeline-animation>
<a-timeline-animation select="a-entity[mixin~=box]" name="scale"></a-timeline-animation>
<a-timeline-animation select="a-entity[mixin~=box]" name="color"></a-timeline-animation>
</a-timeline-group>
<a-timeline-group>
<a-timeline-animation select="#text2" name="togglevisible"></a-timeline-animation>
<a-timeline-animation select="#text2" name="fadein"></a-timeline-animation>
<a-timeline-animation select="#text2" name="textcolor"></a-timeline-animation>
</a-timeline-group>
<a-timeline-animation select="#text2" name="fadeout"></a-timeline-animation>
<a-timeline-animation select="#text2" name="togglevisibleoff"></a-timeline-animation>
<a-timeline-animation select="#text3" name="togglevisible"></a-timeline-animation>
<a-timeline-group>
<a-timeline-animation select="a-entity[mixin~=box]" name="color"></a-timeline-animation>
<a-timeline-animation select="a-entity[mixin~=box]" name="rotate"></a-timeline-animation>
<a-timeline-animation select="a-entity[mixin~=box]" name="position"></a-timeline-animation>
<a-timeline-animation select="#text3" name="fadein"></a-timeline-animation>
<a-timeline-animation select="#text3" name="positionin"></a-timeline-animation>
</a-timeline-group>
<a-timeline-animation select="#text3" name="positionout"></a-timeline-animation>
<a-timeline-animation select="#text3" name="togglevisibleoff"></a-timeline-animation>
<a-timeline-animation select="#text4" name="togglevisible"></a-timeline-animation>
<a-timeline-group>
<a-timeline-animation select="#sky" name="color"></a-timeline-animation>
<a-timeline-animation select="#text4" name="fadein"></a-timeline-animation>
</a-timeline-group>
<a-timeline-animation select="#text4" name="fadeout" offset="500"></a-timeline-animation>
</a-timeline>
<a-mixin id="box"
geometry="primitive: box"
material="color: #AAA; opacity: 0"
animation__fadein="property: material.opacity; dur: 2000; from: 0; to: 1; autoplay: false"
animation__scale="property: scale; to: 2 20 2; dur: 2000; easing: easeInOutElastic; autoplay: false"
animation__position="property: position; to: 0 30 -3; dur: 2000; autoplay: false"
animation__color="property: material.color; from: #AAA; to: #222; dur: 2500; autoplay: false"
animation__rotate="property: rotation; to: 0 360; dur: 1000; easing: easeInQuad; autoplay: false"
scale="0.0001 0.0001 0.0001"
></a-mixin>
<a-mixin id="text"
text="align: center; color: #333; width: 6; opacity: 0"
animation__fadein="property: text.opacity; from: 0; to: 1; dur: 3000; easing: linear; autoplay: false"
animation__fadeout="property: text.opacity; from: 1; to: 0; dur: 3000; easing: linear; autoplay: false"
animation__togglevisible="property: visible; from: false; to: true; dur: 1; autoplay: false"
animation__togglevisibleoff="property: visible; from: true; to: false; dur: 1; autoplay: false"
position="0 2 -3"
visible="false"></a-mixin>

Related

Create transparent background image from text input

i just trying to do create image from text input value which i want to transparent background, but somehow somewhere there is a mistake which i couldn't find. http://jsfiddle.net/e4f3Lc6n/
When i change the var backgroundColor = "transparent"; to any color it works like a charm. but you can see in jsfiddle link it is writing over the previous text when it is transparent. For my project there should be no color background. Where am i making a mistake?
Thanks for any help...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Text Arranger</title>
<link rel="stylesheet" href="../poetry/poetry_stylesheet.css" type="text/css"/>
<link rel="stylesheet" href="../index_stylesheet.css" type="text/css"/>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-46245008-1', 'peteymac.com');
ga('send', 'pageview');
</script>
<script type="text/javascript">
window.addEventListener("load", eventWindowLoaded, false);
var Debugger = function() {};
Debugger.log = function(message) {
try {
console.log(message);
} catch (exception) {
return;
}
}
function eventWindowLoaded () {
canvasApp();
}
function canvasSupport () {
return !!document.createElement("canvas").getContext;
}
function canvasApp () {
Debugger.log("Drawing Canvas");
if(!canvasSupport()) {
return;
}
var theCanvas = document.getElementById('canvasOne');
var context = theCanvas.getContext('2d');
WIDTH = theCanvas.width;
HEIGHT = theCanvas.height;
var message = "canberk";
var fontSize = "50";
var fontFace = "serif";
var fontWeight = "normal"
var fontStyle = "normal";
var textFillColor = "#ff0000";
var backgroundColor = "transparent";
var textStrokeColor = "#000000";
var fillOrStroke = "fill";
var textBaseline = "middle";
var textAlign = "center";
var fillType = "colorFill";
// This is the event handler for listening for a key up event in the text box form
// It will call the textBoxChanged function to update the text in the canvas
var formElement = document.getElementById("textBox");
formElement.addEventListener("keyup", textBoxChanged, false);
formElement = document.getElementById("textSize");
formElement.addEventListener("change", textSizeChanged, false);
formElement = document.getElementById("textFont");
formElement.addEventListener("change", textFontChanged, false);
formElement = document.getElementById("fontWeight");
formElement.addEventListener("change", fontWeightChanged, false);
formElement = document.getElementById("fontStyle");
formElement.addEventListener("change", fontStyleChanged, false);
formElement = document.getElementById("fillType");
formElement.addEventListener("change", fillTypeChanged, false);
formElement = document.getElementById("textFillColor");
formElement.addEventListener("change", textFillColorChanged, false);
formElement = document.getElementById("createImageData");
formElement.addEventListener("click", createImageDataPressed, false);
drawScreen();
function drawScreen() {
var metrics = context.measureText(message);
var textWidth = metrics.width;
var xPosition = WIDTH / 2
var yPosition = HEIGHT / 2;
// Draws the Text Box
context.globalAlpha = 1.0;
context.fillStyle = backgroundColor;
context.fillRect(0,0,WIDTH,HEIGHT);
// Draws the actual text
context.font = fontWeight + " " + fontStyle + " " + fontSize + "px " + fontFace;
context.textBaseline = textBaseline;
context.textAlign = textAlign;
var tempColor;
switch(fillType) {
case "colorFill":
Debugger.log("Color Fill");
tempColor = textFillColor;
break;
case "linearGradient":
Debugger.log("Linear Gradient");
var linGradient = context.createLinearGradient(xPosition-textWidth/2, yPosition, xPosition+textWidth/2, yPosition);
linGradient.addColorStop(0, textFillColor);
tempColor = linGradient;
break;
case "radialGradient":
Debugger.log("Radial Gradient");
var radGradient = context.createRadialGradient(xPosition, yPosition, 1, xPosition, yPosition, textWidth/2);
radGradient.addColorStop(0, textFillColor);
tempColor = radGradient;
break;
}
switch(fillOrStroke) {
case "fill":
context.fillStyle = tempColor;
context.fillText(message, xPosition, yPosition);
break;
case "stroke":
context.strokeStyle = textStrokeColor;
context.strokeText(message, xPosition, yPosition);
break;
case "both":
context.fillStyle = tempColor;
context.fillText(message, xPosition, yPosition);
context.strokeStyle = textStrokeColor;
context.strokeText(message, xPosition, yPosition);
break;
}
}
function textBoxChanged(e) {
var target = e.target;
message = target.value;
drawScreen();
}
function textSizeChanged(e) {
var target = e.target;
fontSize = target.value;
drawScreen();
}
function textFontChanged(e) {
var target = e.target;
fontFace = target.value;
drawScreen();
}
function fontWeightChanged(e) {
var target = e.target;
fontWeight = target.value;
drawScreen();
}
function fontStyleChanged(e) {
var target = e.target;
fontStyle = target.value;
drawScreen();
}
function fillTypeChanged(e) {
var target = e.target;
fillType = target.value;
drawScreen();
}
function textFillColorChanged(e) {
var target = e.target;
textFillColor = "#" + target.value;
drawScreen();
}
function createImageDataPressed(e) {
var imageDataDisplay = document.getElementById("imageDataDisplay");
imageDataDisplay.value = theCanvas.toDataURL();
}
}
</script>
<style>
#canvasOne {
box-shadow: -4px -4px 5px #aaaaaa;
display: block;
margin-left: -60px;
}
form {
margin-top: 40px;
}
</style>
</head>
<body>
<canvas id="canvasOne" width="1000" height="250">
Your browser does not support Canvas.
</canvas>
<form>
Text: <input id="textBox" value="canberk"/>
<br/>
Text Font: <select id="textFont">
<option value = "serif">Serif</option>
<option value = "sans-serif">Sans-Serif</option>
<option value = "cursive">Cursive</option>
<option value = "fantasy">Fanatasy</option>
<option value = "monospace">Monospace</option>
</select>
Font Weight: <select id="fontWeight">
<option value="normal">Normal</option>
<option value="bold">Bold</option>
<option value="bolder">Bolder</option>
<option value="lighter">Lighter</option>
</select>
Font Style: <select id="fontStyle">
<option value="normal">Normal</option>
<option value="italic">Italic</option>
<option value="oblique">Oblique</option>
</select>
<br/>
Text Size: <input type="range" id="textSize"
min="0"
max="200"
step="1"
value="50"/>
<br/>
Fill Type: <select id="fillType">
<option value="colorFill">Color Fill</option>
<option value="linearGradient">Linear Gradient</option>
<option value="radialGradient">Radial Gradient</option>
</select>
<br/>
Text Fill Color: <input id="textFillColor" value="ff0000"/>
<input type="button" id="createImageData" value="Create Data Image">
<br/>
<textarea id="imageDataDisplay" rows=5 cols=100></textarea>
</form>
</div>
</body>
</html>
I think the solution you need is:
function drawScreen() {
context.clearRect(0, 0, WIDTH, HEIGHT);
...
...
}

svg.js, click event does not fire when animation is running

I try to bind a click event on symbol in a svg.
When a element spinns in the symbol, the click event is not fired, stops/pauses the animation, the click event fires.
How can i fix this, that the click events get fired every time i click on it, regardless if the animations run or not.
.as-console-wrapper{
display: none!important;
}
<!doctype html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Schematic</title>
<script src="https://cdn.jsdelivr.net/npm/#svgdotjs/svg.js#3.0/dist/svg.min.js"></script>
<!--<script src="assets/js/vue.min.js"></script>-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.12/vue.common.dev.min.js"></script>
<script>
const color = {
blue: "#007bff",
indigo: "#6610f2",
purple: "#6f42c1",
pink: "#e83e8c",
red: "#dc3545",
orange: "#fd7e14",
yellow: "#ffc107",
green: "#28a745",
teal: "#20c997",
cyan: "#17a2b8",
white: "#fff",
gray: "#6c757d",
"gray-dark": "#343a40",
primary: "#007bff",
secondary: "#6c757d",
success: "#28a745",
info: "#17a2b8",
warning: "#ffc107",
danger: "#dc3545",
light: "#f8f9fa",
dark: "#343a40"
};
let baseColor = {
background: "#000",
"fill-opacity": 0.5,
stroke: color.white,
"stroke-width": 1,
"stroke-opacity": 0.5
};
let pipeColor = {
fill: color.blue,
opacity: 1
};
let pumpColor = {
fill: color.gray,
"fill-opacity": 0.8
}
document.addEventListener("DOMContentLoaded", () => {
// parent drawing
let draw = SVG().addTo('#schematic').size("100%", 500);
let pumpGroup = draw.symbol();
pumpGroup.click(function () {
alert("Pump clicked!");
});
let height = 50;
let radius = 30;
let chase = pumpGroup.rect(80, height).attr(baseColor).move(0, 0); // 520, 370
let motor1 = pumpGroup.circle(radius).attr(pumpColor).move(45, (height / 2) - radius / 2); // 525, 380
let motor2 = pumpGroup.circle(radius).attr(pumpColor).move(5, (height / 2) - radius / 2); // 565, 380
let fan1 = pumpGroup.image("https://cdn0.iconfinder.com/data/icons/screw/512/fan-ventilator-propeller-rotor-motion-512.png").scale(0.05).move(940, 240); //.animate().rotate(360, 256 + 940, 256 + 240).loop();
let fan2 = pumpGroup.image("https://cdn0.iconfinder.com/data/icons/screw/512/fan-ventilator-propeller-rotor-motion-512.png").scale(0.05).move(140, 240);
//
// 1 = slave, 2 = master
let fant1Runner = fan1.animate(1500).ease("-").rotate(360, 256 + 940, 256 + 240).loop().timeline().pause();
let fant2Runner = fan2.animate(1500).ease("-").rotate(360, 256 + 140, 256 + 240).loop().timeline().pause();
setInterval(() => {
fant2Runner.play();
fant1Runner.play();
setTimeout(() => {
fant2Runner.pause();
fant1Runner.pause();
}, 2500)
}, 5000);
draw.use(pumpGroup).move(10, 10).click(() => {
alert("Clicked on pump!");
});
});
</script>
</head>
<body>
<div id="app">
<div id="schematic"></div>
</div>
</body>
</html>
For demsonstation i create a minimal snippet.
The fans start spinning after 5sec, run then for 2.5 sec and stops.
As written above, when the fans spin, no click fires.
Thanks for any advise.

Rotate marker with animation in Openlayers

I have this code:
this.posFeature = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.fromLonLat([-5.7,43.5])),
name: 'pos'
});
var posStyle = new ol.style.Style({
image: new ol.style.Icon({
anchor: [10, 10],
anchorXUnits: 'pixels',
anchorYUnits: 'pixels',
src: 'car.svg'
})
});
this.posFeature.setStyle(posStyle);
this.markerPosSource = new ol.source.Vector({features: [this.posFeature]});
this.layerPos = new ol.layer.Vector({source: this.markerPosSource});
map.addLayer(this.layerPos);
I would like to rotate the icon with an animation (in its rotation). Is it possible? If not, how to rotate without animation?
Thanks in advance!
To smoothly animate a rotation calculate the required rotation based on elapsed time each time the map rendered, e.g. for a complete rotation every 10 seconds:
<!DOCTYPE html>
<html>
<head>
<title>Icon Symbolizer</title>
<link rel="stylesheet" href="https://openlayers.org/en/v6.4.3/css/ol.css" type="text/css">
<script src="https://openlayers.org/en/v6.4.3/build/ol.js"></script>
<style>
html, body, .map {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<script>
var iconFeature = new ol.Feature({
geometry: new ol.geom.Point([0, 0]),
name: 'Null Island',
population: 4000,
rainfall: 500
});
var iconStyle = new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 1],
src: 'https://openlayers.org/en/v6.4.3/examples/data/icon.png'
})
});
iconFeature.setStyle(iconStyle);
var vectorSource = new ol.source.Vector({
features: [iconFeature]
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource
});
var map = new ol.Map({
layers: [vectorLayer],
target: document.getElementById('map'),
view: new ol.View({
center: [0, 0],
zoom: 3
})
});
var startTime = new Date().getTime();
map.on('rendercomplete', function(e) {
var elapsedTime = e.frameState.time - startTime;
var rotation = elapsedTime / 10000 * Math.PI;
iconStyle.getImage().setRotation(rotation);
iconFeature.changed();
});
</script>
</body>
</html>
To rotate it use rotation (NB use radians not degrees)
var posStyle = new ol.style.Style({
image: new ol.style.Icon({
anchor: [10, 10],
anchorXUnits: 'pixels',
anchorYUnits: 'pixels',
src: 'car.svg',
rotation: Math.PI/2
})
});

put canvas in custom div?

I started developing from an example that shows to integrate three.js + greensock.
Link: http://www.kadrmasconcepts.com/blog/2012/05/29/greensock-three-js/
I am trying to put canvas used by three.js + greensock to a div inside my page designed. But canvas always gets appended to bottom of screen. I tried to do getelementbyid and access my div object but did not work.
Current:
https://www.dropbox.com/s/kowowsjvdnwkl0f/bart.png?dl=0
As current implementation shows canvas is below blue panel but want it to be inside red panel (div).
Can someone help me fix it. I am attaching my code below...Thank you very much in advance!
php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Horse Demo</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="author" content="Jason Kadrmas" />
<!-- Bootstrap Core CSS -->
<link href="bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- MetisMenu CSS -->
<link href="bower_components/metisMenu/dist/metisMenu.min.css" rel="stylesheet">
<!-- Timeline CSS -->
<link href="css/timeline.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="css/sb-admin-2.css" rel="stylesheet">
<!-- Morris Charts CSS -->
<link href="bower_components/morrisjs/morris.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="bower_components/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<!-- jQuery -->
<script src="bower_components/jquery/dist/jquery.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- Metis Menu Plugin JavaScript -->
<script src="bower_components/metisMenu/dist/metisMenu.min.js"></script>
<!-- Morris Charts JavaScript -->
<script src="bower_components/raphael/raphael-min.js"></script>
<script src="bower_components/morrisjs/morris.min.js"></script>
<script src="js/morris-data.js"></script>
<!-- Custom Theme JavaScript -->
<script src="js/sb-admin-2.js"></script>
<link href='http://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
<link href='css/simple.css' rel='stylesheet' type='text/css'>
<script type="text/javascript" src="js/lib/plugins/CSSPlugin.min.js"></script>
<script type="text/javascript" src="js/lib/easing/EasePack.min.js"></script>
<script type="text/javascript" src="js/lib/TimelineLite.min.js"></script>
<script type="text/javascript" src="js/lib/TweenLite.min.js"></script>
<!--<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>-->
<script type="text/javascript" src="js/lib/Three.js"></script>
<script type="text/javascript" src="js/ThreeScene.js"></script>
</head>
<body>
<div class="wrapper">
<!-- <div class="navbar-inner">
<div class="container">
<span class="btn-navheader">Timeline Demo - Horse</span>
Reset
Pause
Start
</div>
</div>-->
<!-- Navigation -->
<nav class="navbar navbar-default navbar-static-top" role="navigation" style="margin-bottom: 0">
<div class="navbar-header">
<a class="navbar-brand">Balloon Task v1.0</a>
</div>
<!-- /.navbar-header -->
</nav>
<div class="container-fluid">
<div class="row">
<div class="col-lg-3 col-md-6">
<div class="panel panel-primary">
<div class="panel-heading">
<div class="row">
<div class="col-xs-6 text-left">
<div class="">Balloon Number</div>
</div>
<div class="col-xs-6 text-right">
<div class="huge">1/30</div>
</div>
</div>
</div>
<a href="#">
<div class="panel-footer">
<span class="pull-left">View Details</span>
<div class="clearfix"></div>
</div>
</a>
</div>
</div>
<div class="col-lg-9 col-md-18">
<div class="panel panel-red">
<div class="panel-heading">
<div class="row">
<div id="taskcanvas" class="canvas">
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row bottom-container">
<div class="col-md-12">
<span>Timeline Demo - Horse</span>
Reset
Pause
Start
</div>
</div>
</div>
</div>
<!-- /#wrapper -->
<script language="javascript" type="text/javascript">
var width = 500,
height = 500,
camera,
scene,
renderer,
SHADOW_MAP_WIDTH = 2048,
SHADOW_MAP_HEIGHT = 2048,
dominoGeometry,
dominoMaterial,
dominoPos = -180,
tweens = [],
type = 0,
d = 8,
basicScene,
tl = new TimelineLite({onComplete: complete});
init();
function init() {
basicScene = new THREE.BasicScene({width: width, height: height});
TweenLite.ticker.addEventListener("tick", render);
initObjects();
}
// Horse morph variables.
var horse;
var paused = true;
var theta = 0;
var duration = 2100;
var keyframes = 15, interpolation = duration / keyframes;
var lastKeyframe = 0, currentKeyframe = 0;
function render() {
basicScene.renderer.render(basicScene.scene, basicScene.camera);
if (horse && !paused) {
// Alternate morph targets
var time = Date.now() % duration;
var keyframe = Math.floor(time / interpolation);
if (keyframe != currentKeyframe) {
horse.morphTargetInfluences[ lastKeyframe ] = 0;
horse.morphTargetInfluences[ currentKeyframe ] = 1;
horse.morphTargetInfluences[ keyframe ] = 0;
lastKeyframe = currentKeyframe;
currentKeyframe = keyframe;
}
horse.morphTargetInfluences[ keyframe ] = (time % interpolation) / interpolation;
horse.morphTargetInfluences[ lastKeyframe ] = 1 - horse.morphTargetInfluences[ keyframe ];
}
}
function initObjects() {
dominoGeometry = new THREE.CubeGeometry(100, 100, 100, 1, 1, 1);
dominoMaterial = new THREE.MeshPhongMaterial();
dominoMaterial.color = new THREE.Color().setRGB(1, 1, 1);
dominoMaterial.ambient = new THREE.Color().setRGB(0.0196078431372549, 0.0196078431372549, 0.0196078431372549);
dominoMaterial.specular = new THREE.Color().setRGB(0.06666666666666667, 0.06666666666666667, 0.06666666666666667);
var light = new THREE.DirectionalLight();
light.intensity = 0.7;
light.castShadow = true;
light.position.set(-320, 350, 100);
basicScene.add(light);
// Floor
var geometry = new THREE.PlaneGeometry(1800, 800, 3, 3);
var material = new THREE.MeshPhongMaterial({color: 0xffffff, wireframe: false});
material.ambient = new THREE.Color().setRGB(0.0196078431372549, 0.0196078431372549, 0.0196078431372549);
material.specular = new THREE.Color().setRGB(0.06666666666666667, 0.06666666666666667, 0.06666666666666667);
var mesh = new THREE.Mesh(geometry, material);
mesh.receiveShadow = true;
mesh.position.set(0, -50, 0);
basicScene.add(mesh);
initDominoes();
initHorse();
}
function initDominoes() {
var mesh, i;
for (i = 0; i < 4; i++) {
mesh = new THREE.Mesh(dominoGeometry, dominoMaterial);
mesh.position.set(dominoPos, 0, 0);
mesh.rotationAutoUpdate = false;
mesh.castShadow = true;
mesh.receiveShadow = false;
mesh.scale.set(0.1, 1, 0.4);
basicScene.add(mesh);
dominoPos += 50;
tweens.push(TweenLite.to(mesh.rotation, 2, {y: Math.PI * 2, ease: Bounce.easeOut, delay: d * 0.1 + i * 0.2}));
}
}
function initHorse() {
var loader = new THREE.JSONLoader(true);
loader.load("models/horse.js", function (geometry) {
horse = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({color: 0x0aa8a5, morphTargets: true}));
horse.scale.set(0.75, 0.75, 0.75);
horse.position.set(-600, -50, 0);
horse.rotation.y = Math.PI / 2;
basicScene.add(horse);
// Click handlers
$('.start').on('click', start).show();
$('.pause').on('click', pause).show();
$('.reset').on('click', complete).show();
// Horse
tweens.push(TweenLite.to(horse.position, d, {x: 900}));
tweens.push(TweenLite.to(horse.position, d * 0.1, {y: 150, delay: d * 0.07, ease: Sine.easeOut}));
tweens.push(TweenLite.to(horse.position, d * 0.12, {y: -50, delay: d * 0.18, ease: Sine.easeIn}));
tl.insertMultiple(tweens);
tl.pause();
});
}
function pause() {
paused = true;
tl.pause();
}
function start() {
paused = false;
tl.play();
}
function complete() {
pause();
tl.progress(0);
}
</script>
</body>
</html>
JS:
THREE.BasicScene = function( args ) {
var container = document.getElementById( "taskcanvas" );
var _this = this;
this.width = args.width;
this.height = args.height;
// Setup scene, camera, and renderer
this.scene = new THREE.Scene();
this.camera = initCamera( this.scene );
this.renderer = initRenderer();
container.appendChild( this.renderer.domElement );
container = document.body.appendChild( container );
container.appendChild( this.renderer.domElement );
function initCamera( scene ) {
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.z = 380;
camera.aspect = _this.width / _this.height;
camera.updateProjectionMatrix();
scene.add( camera );
return camera;
}
function initRenderer() {
var renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setSize( _this.width, _this.height );
renderer.shadowCameraNear = 3;
renderer.shadowCameraFar = _this.camera.far;
renderer.shadowCameraFov = 50;
renderer.shadowMapBias = 0.0039;
renderer.shadowMapDarkness = 0.3;
renderer.shadowMapWidth = SHADOW_MAP_WIDTH;
renderer.shadowMapHeight = SHADOW_MAP_HEIGHT;
renderer.shadowMapEnabled = true;
renderer.shadowMapSoft = true;
return renderer;
}
};
THREE.BasicScene.prototype = {
add: function( obj ) {
this.scene.add( obj );
}
};
CSS:
canvas {
background-image: -webkit-linear-gradient(top, #cee4ff, #fff3e1);
background-image: linear-gradient(to bottom, #cee4ff, #fff3e1);
background-image: -moz-linear-gradient(top, #cee4ff, #fff3e1); //FF3.6+
background-image: -ms-linear-gradient(top, #cee4ff, #fff3e1); //IE10
background-image: -o-linear-gradient(top, #cee4ff, #fff3e1); //Opera 11.10+
}
You might have moved container out by accident
container = document.body.appendChild( container );
container.appendChild( this.renderer.domElement );
Will cause the container to be on body, which will show up at the bottom.
#Vinay had the right answer, you can give the renderer constructor a canvas so you can make your own canvas in the container, then pass that canvas directly to the renderer.

x3dom rotation not working when using toAxisAngle(). Element follows mouse correctly, but does not rotate correctly

I have a page that I am creating that is similar to a game with a bird's eye view. I am trying to move a x3dom element on the x and z axis based on a mouse move event. It works except it isn't rotated correctly. The element called placeholder is the one that I am moving based on the mouse coordinates. Under the function squaremousemove(), you'll notice the rotation of rot[1]. I tried replacing this with rotateIncrement which is how I rotate all the other elements, but this didn't work. The place holder is suppose to have the same rotation as the square. Any ideas?
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" href="style/x3dom.css">
<script type="text/javascript" charset="utf-8" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" charset="utf-8" src="js/x3dom.js"></script>
<style>
body {margin: 0; padding: 0;}
#debugtext {position: absolute; top: 30px; left: 15px;}
</style>
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
var screenW = $(document).width();
var screenH = $(document).height();
var rotateIncrement = 0.78;
var groundlevel = 0.1;
var isMouseDown = false;
var isShiftPressed = false;
var isCtrlPressed = false;
var lastrotatevalueX = 0;
var lastpanvalueX = 0;
var lastpanvalueZ = 0;
var panincrementX = 0;
var panincrementZ = 200;
var x3d = document.getElementById('x3darea');
// set the height and width of the x3d area
$("#x3darea").css({width: screenW + "px", height: screenH + "px", border: "0"});
// set viewpoint attributes
viewpoint.setAttribute("position", "0 65 200");
viewpoint.setAttribute("orientation", "1 0 0 -0.5");
// set initial rotation
rotateshapes();
// disable selection for all elements
$(document).disableSelection();
$(document).keydown(function(e) {
if (e.shiftKey)
isShiftPressed = true;
if (e.ctrlKey)
isCtrlPressed = true;
});
$(document).keyup(function(e) {
isShiftPressed = false;
isCtrlPressed = false;
});
x3d.addEventListener("mousedown", function() {
isMouseDown = true;
}, false);
x3d.addEventListener("mouseup", function() {
isMouseDown = false;
}, false);
x3d.addEventListener("mousemove", function(e) {
if (isMouseDown) {
if (isShiftPressed)
rotatesetup(e);
if (isCtrlPressed) {
panviewbox(e);
}
// not sure what these two lines do except that they disable the built-in rotation and panning
e.cancelBubble = true;
e.stopPropagation();
}
}, true);
function panviewbox(e) {
var increment = 0.4;
if (lastpanvalueX > e.layerX)
panincrementX += increment;
else
panincrementX -= increment;
if (lastpanvalueZ > e.layerY)
panincrementZ += increment;
else
panincrementZ -= increment;
lastpanvalueX = e.layerX;
lastpanvalueZ = e.layerY;
viewpoint.setAttribute("position", panincrementX + " 65 " + panincrementZ);
}
function rotatesetup(e) {
var increment = 0.06;
if (lastrotatevalueX > e.layerX)
rotateIncrement += increment;
else
rotateIncrement -= increment;
lastrotatevalueX = e.layerX;
rotateshapes(e);
}
function rotateshapes() {
$(".rotatable").each(function() {
gridline = document.getElementById($(this).attr('id'));
gridline.setAttribute('rotation', '0 1 0 ' + rotateIncrement);
});
}
});
function squaremousemove(event) {
var posX = event.worldX;
var posZ = event.worldZ;
var placeholder = document.getElementById('placeholder');
var norm = new x3dom.fields.SFVec3f(event.normalX, event.normalY, event.normalZ);
var qDir = x3dom.fields.Quaternion.rotateFromTo(new x3dom.fields.SFVec3f(0, 1, 0), norm);
var rot = qDir.toAxisAngle();
$("#debugtext").html(rot[1]);
// $("#debugtext").html(posX.toFixed(4) + ", " + posZ.toFixed(4));
placeholder.setAttribute('rotation', rot[0].x + ' 1 ' + rot[0].z + ' ' + rot[1]);
placeholder.setAttribute('translation', event.worldX + ' 0.1 ' + event.worldZ);
placeholder.setAttribute('center', (event.worldX*-1) + ' 0 ' + (event.worldZ*-1));
// placeholder.setAttribute('translation', posX + ' 1 ' + posZ);
// placeholder.setAttribute('rotation', '0 1 0 ' + rotateIncrement);
}
</script>
</head>
<body>
<div id="devcontent">
<span id="debugtext"></span>
<x3d id="x3darea">
<scene>
<transform id="square" class="rotatable" onmousemove="squaremousemove(event);" translation="0 0 0">
<shape>
<appearance>
<material diffuseColor='green'></material>
</appearance>
<box size="200 0.01 200" />
</shape>
</transform>
<transform id="placeholder" class="rotatable" translation="-95 0.1 91" center="95 0 -91">
<shape>
<appearance>
<material diffuseColor='#ff8787'></material>
</appearance>
<box size="6 0.1 6" />
</shape>
</transform>
<transform id="building1" class="rotatable" translation="-40 2 20" center="40 0 -20">
<shape>
<appearance>
<material diffuseColor='blue'></material>
</appearance>
<box size="2 4 2" />
</shape>
</transform>
<transform id="building2" class="rotatable" translation="5 2.5 18" center="-5 0 -18">
<shape>
<appearance>
<material diffuseColor='yellow'></material>
</appearance>
<box size="4 5 4" />
</shape>
</transform>
<transform id="road1" class="rotatable" translation="0 0.1 0" center="0 0 0">
<shape>
<appearance>
<material diffuseColor='gray'></material>
</appearance>
<box size="200 0.001 2" />
</shape>
<Viewpoint id="viewpoint" />
</scene>
</x3d>
</div>
</body>
</html>

Resources