Syntax problem when using THREE.TextureLoader - javascript

I'm trying a panoramic viewer code which its three.js version is r68,and I update the three.js version into r121 in order to use raycaster function.
The problem happen when I revise the code:
var texture = THREE.ImageUtils.loadTexture('img/pano2.jpg', new THREE.UVMapping(), function() {
init();
animate();
});
into
var loader = new THREE.TextureLoader();
loader.load(
'img/demo.jpg',
function(texture){
var material = new THREE.MeshBasicMaterial({map: texture});
},
function(){
init();
animate();
},
function ( err ) {
console.error( 'An error happened.' );
}
);
No error pop up but the render function(included in init function) and animate function doesn't progress.
I'm not sure it's texture's problem or init function's problem.
If somebody can give me some suggestion, I'll be really grateful.
I take this as my reference:
https://threejs.org/docs/#api/en/loaders/TextureLoader
Three.TextureLoader is not loading images files
And here is my full code:
<!DOCTYPE html>
<html>
<head>
<title>Panorama1</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
html{
margin: 0;
padding: 0;
text-align: center;
}
body {
font-size: 18px;
line-height: 1.5em;
position: relative;
width: 100%;
height: 100%;
margin: 40px auto;
padding: 0;
display: inline-block;
/*max-width: 100%;
/*max-width: 1440px;*/
overflow-x: hidden;
}
a{
color: #528CE0;
}
#demo{
/* comment for fixed dimentsions */
position: relative;
width: 1440px;
height: 650px;
margin: 0 auto;
overflow: hidden;
cursor: move; /* fallback if grab cursor is unsupported */
cursor: grab;
cursor: -moz-grab;
cursor: -webkit-grab;
}
#demo:active {
cursor: grabbing;
cursor: -moz-grabbing;
cursor: -webkit-grabbing;
}
#log{
position: absolute;
background: #fff;
padding: 20px;
bottom: 20px;
left: 20px;
width: 150px;
font: normal 12px/18px Monospace, Arial, Helvetical, sans-serif;
text-align: left;
border: 3px double #ddd;
}
#description{
display: inline-block;
width: 100%;
max-width: 600px;
text-align: left;
}
</style>
</head>
<body>
<h1>A panoramic experiment with Three.JS</h1>
<h2>pano1</h2>
<div id="demo">
<div id="log"></div>
</div>
<div id="description">
</div>
<script src="libs/threejs/build/three.min.js"></script>
<script>
"use strict";
var camera,
scene,
element = document.getElementById('demo'), // Inject scene into this
renderer,
onPointerDownPointerX,
onPointerDownPointerY,
onPointerDownLon,
onPointerDownLat,
fov = 45, // Field of View
isUserInteracting = false,
lon = 0,
lat = 0,
phi = 0,
theta = 0,
onMouseDownMouseX = 0,
onMouseDownMouseY = 0,
onMouseDownLon = 0,
onMouseDownLat = 0,
width = 1440, // int || window.innerWidth
height = 650, // int || window.innerHeight
ratio = width / height;
var mouse = new THREE.Vector2();
var loader = new THREE.TextureLoader();
loader.load(
'img/demo.jpg',
function(texture){
var material = new THREE.MeshBasicMaterial({map: texture});
},
function(){
init();
animate();
},
function ( err ) {
console.error( 'An error happened.' );
}
);
//const loader = new THREE.TextureLoader();
//var texture = THREE.ImageUtils.loadTexture('img/pano2.jpg', new THREE.UVMapping(), function() {
//init();
//animate();
//});
function init() {
camera = new THREE.PerspectiveCamera(fov, ratio, 1, 1000);
scene = new THREE.Scene();
var mesh = new THREE.Mesh(new THREE.SphereGeometry(500, 60, 40), material);
mesh.scale.x = -1;
scene.add(mesh);
renderer = new THREE.WebGLRenderer({antialias: true});
renderer.setSize(width, height);
element.appendChild(renderer.domElement);
element.addEventListener('mousedown', onDocumentMouseDown, false);
element.addEventListener('mousewheel', onDocumentMouseWheel, false);
element.addEventListener('DOMMouseScroll', onDocumentMouseWheel, false);
window.addEventListener('resize', onWindowResized, false);
onWindowResized(null);
}
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
var raycaster = new THREE.Raycaster();
raycaster.setFromCamera( mouse, camera );
lat = Math.max(-85, Math.min(85, lat));
phi = THREE.Math.degToRad(90 - lat);
theta = THREE.Math.degToRad(lon);
camera.position.x = 100 * Math.sin(phi) * Math.cos(theta);
camera.position.y = 100 * Math.cos(phi);
camera.position.z = 100 * Math.sin(phi) * Math.sin(theta);
var log = ("x: " + camera.position.x);
log = log + ("<br/>y: " + camera.position.y);
log = log + ("<br/>z: " + camera.position.z);
log = log + ("<br/>fov: " + fov);
document.getElementById('log').innerHTML = log;
camera.lookAt(scene.position);
renderer.render(scene, camera);
}
function onWindowResized(event) {
// renderer.setSize(window.innerWidth, window.innerHeight);
// camera.projectionMatrix.makePerspective(fov, window.innerWidth / window.innerHeight, 1, 1100);
renderer.setSize(width, height);
camera.updateProjectionMatrix();
}
function onDocumentMouseDown(event) {
event.preventDefault();
onPointerDownPointerX = event.clientX;
onPointerDownPointerY = event.clientY;
onPointerDownLon = lon;
onPointerDownLat = lat;
isUserInteracting = true;
element.addEventListener('mousemove', onDocumentMouseMove, false);
element.addEventListener('mouseup', onDocumentMouseUp, false);
}
function onDocumentMouseMove(event) {
if (fov < 10){
lon = (event.clientX - onPointerDownPointerX) * -0.01 + onPointerDownLon;
lat = (event.clientY - onPointerDownPointerY) * -0.01 + onPointerDownLat;
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
}
else{
lon = (event.clientX - onPointerDownPointerX) * -0.175 + onPointerDownLon;
lat = (event.clientY - onPointerDownPointerY) * -0.175 + onPointerDownLat;
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
}
}
function onDocumentMouseUp(event) {
isUserInteracting = false;
element.removeEventListener('mousemove', onDocumentMouseMove, false);
element.removeEventListener('mouseup', onDocumentMouseUp, false);
}
function onDocumentMouseWheel(event) {
// WebKit
if (event.wheelDeltaY) {
fov -= event.wheelDeltaY * 0.05;
// Opera / Explorer 9
} else if (event.wheelDelta) {
fov -= event.wheelDelta * 0.05;
// Firefox
} else if (event.detail) {
fov += event.detail * 1.0;
}
if (fov < 1 || fov > 55) {
fov = (fov < 1) ? 1 : 55;
}
camera.updateProjectionMatrix();
}
</script>
</body>
</html>
The origin code is :
<!DOCTYPE html>
<html>
<head>
<title>Panorama2</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
html{
margin: 0;
padding: 0;
text-align: center;
}
body {
font-size: 18px;
line-height: 1.5em;
position: relative;
width: 100%;
height: 100%;
margin: 40px auto;
padding: 0;
display: inline-block;
/*max-width: 100%;
/*max-width: 1440px;*/
overflow-x: hidden;
}
a{
color: #528CE0;
}
#demo{
/* comment for fixed dimentsions */
position: relative;
width: 1440px;
height: 650px;
margin: 0 auto;
overflow: hidden;
cursor: move; /* fallback if grab cursor is unsupported */
cursor: grab;
cursor: -moz-grab;
cursor: -webkit-grab;
}
#demo:active {
cursor: grabbing;
cursor: -moz-grabbing;
cursor: -webkit-grabbing;
}
#log{
position: absolute;
background: #fff;
padding: 20px;
bottom: 20px;
left: 20px;
width: 150px;
font: normal 12px/18px Monospace, Arial, Helvetical, sans-serif;
text-align: left;
border: 3px double #ddd;
}
#description{
display: inline-block;
width: 100%;
max-width: 600px;
text-align: left;
}
</style>
</head>
<body>
<h1>A panoramic experiment with Three.JS</h1>
<h2>pano2</h2>
<div id="demo">
<div id="log"></div>
</div>
<div id="description">
</div>
<script src="libs/threejs/build/three.min.js"></script>
<script>
"use strict";
var camera,
scene,
element = document.getElementById('demo'), // Inject scene into this
renderer,
onPointerDownPointerX,
onPointerDownPointerY,
onPointerDownLon,
onPointerDownLat,
fov = 45, // Field of View
isUserInteracting = false,
lon = 0,
lat = 0,
phi = 0,
theta = 0,
onMouseDownMouseX = 0,
onMouseDownMouseY = 0,
onMouseDownLon = 0,
onMouseDownLat = 0,
width = 1440, // int || window.innerWidth
height = 650, // int || window.innerHeight
ratio = width / height;
var texture = THREE.ImageUtils.loadTexture('img/pano2.jpg', new THREE.UVMapping(), function() {
init();
animate();
});
function init() {
camera = new THREE.PerspectiveCamera(fov, ratio, 1, 1000);
scene = new THREE.Scene();
var mesh = new THREE.Mesh(new THREE.SphereGeometry(500, 60, 40), new THREE.MeshBasicMaterial({map: texture}));
mesh.scale.x = -1;
scene.add(mesh);
renderer = new THREE.WebGLRenderer({antialias: true});
renderer.setSize(width, height);
element.appendChild(renderer.domElement);
element.addEventListener('mousedown', onDocumentMouseDown, false);
element.addEventListener('mousewheel', onDocumentMouseWheel, false);
element.addEventListener('DOMMouseScroll', onDocumentMouseWheel, false);
window.addEventListener('resize', onWindowResized, false);
onWindowResized(null);
}
function onWindowResized(event) {
// renderer.setSize(window.innerWidth, window.innerHeight);
// camera.projectionMatrix.makePerspective(fov, window.innerWidth / window.innerHeight, 1, 1100);
renderer.setSize(width, height);
camera.projectionMatrix.makePerspective(fov, ratio, 1, 1100);
}
function onDocumentMouseDown(event) {
event.preventDefault();
onPointerDownPointerX = event.clientX;
onPointerDownPointerY = event.clientY;
onPointerDownLon = lon;
onPointerDownLat = lat;
isUserInteracting = true;
element.addEventListener('mousemove', onDocumentMouseMove, false);
element.addEventListener('mouseup', onDocumentMouseUp, false);
}
function onDocumentMouseMove(event) {
if (fov < 10){
lon = (event.clientX - onPointerDownPointerX) * -0.01 + onPointerDownLon;
lat = (event.clientY - onPointerDownPointerY) * -0.01 + onPointerDownLat;
}
else{
lon = (event.clientX - onPointerDownPointerX) * -0.175 + onPointerDownLon;
lat = (event.clientY - onPointerDownPointerY) * -0.175 + onPointerDownLat;
}
}
function onDocumentMouseUp(event) {
isUserInteracting = false;
element.removeEventListener('mousemove', onDocumentMouseMove, false);
element.removeEventListener('mouseup', onDocumentMouseUp, false);
}
function onDocumentMouseWheel(event) {
// WebKit
if (event.wheelDeltaY) {
fov -= event.wheelDeltaY * 0.05;
// Opera / Explorer 9
} else if (event.wheelDelta) {
fov -= event.wheelDelta * 0.05;
// Firefox
} else if (event.detail) {
fov += event.detail * 1.0;
}
if (fov < 1 || fov > 55) {
fov = (fov < 1) ? 1 : 55;
}
camera.projectionMatrix.makePerspective(fov, ratio, 1, 1100);
}
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
lat = Math.max(-85, Math.min(85, lat));
phi = THREE.Math.degToRad(90 - lat);
theta = THREE.Math.degToRad(lon);
camera.position.x = 100 * Math.sin(phi) * Math.cos(theta);
camera.position.y = 100 * Math.cos(phi);
camera.position.z = 100 * Math.sin(phi) * Math.sin(theta);
var log = ("x: " + camera.position.x);
log = log + ("<br/>y: " + camera.position.y);
log = log + ("<br/>z: " + camera.position.z);
log = log + ("<br/>fov: " + fov);
document.getElementById('log').innerHTML = log;
camera.lookAt(scene.position);
renderer.render(scene, camera);
}
</script>
</body>
</html>
Here is the link to the source code:
https://github.com/NorikDavtian/ThreeJS-360-Panorama
Thanks for your reading !
update:
after trying #prisoner849 's suggestion,the init function and animate function run properly,but the scene still in black both in Chorme or firefox

Try it this way:
var material; // as a global variable
...
loader.load(
'img/demo.jpg',
function(texture){
material = new THREE.MeshBasicMaterial({map: texture});
init();
animate();
},
undefined,
function ( err ) {
console.error( 'An error happened.' );
}
);
In your current option, you call init() and animate() in onProgress callback. Whereas you need to call them in onLoad, thus right after material = new THREE.MeshBasicMaterial({map: texture});.

Related

Tried making a button, that takes you to google page

i have a html script with button and onclick function script that should take me to google.com, but it doesn't seem to work. Been stuck with this for hours. Im also new to HTML.
Tried everything. Line 336 and 353 should be the needed content. And line 136 should be the button itself. I don't understand whats wrong. Anyone ever have had this issue?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="shortcut icon" type="image/x-icon/text/javascript" href="https://static.codepen.io/assets/favicon/favicon-aec34940fbc1a6e787974dcd360f2c6b63348d4b1f4e06c77743096d55480f33.ico" />
<link rel="mask-icon" type="" href="https://static.codepen.io/assets/favicon/logo-pin-8f3771b1072e3c38bd662872f6b673a722f4b3ca2421637d5596661b4e2132cc.svg" color="#111" />
<title>SpyBanter - SpyBanter's Official WebSite</title>
<style type="text/css">
body {
overflow: hidden;
margin: 0;
}
body:before {
content: '';
background: #c4252a url(http://subtlepatterns2015.subtlepatterns.netdna-cdn.com/patterns/cheap_diagonal_fabric.png);
background-blend-mode: multiply;
mix-blend-mode: multiply;
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
z-index: 10;
}
canvas {
opacity: 0;
transition: 1s opacity cubic-bezier(0.55, 0, 0.1, 1);
}
canvas.ready {
opacity: 0.4;
}
.intro {
position: absolute;
padding: 20px;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
left: 50%;
top: 50%;
text-align: center;
color: #fafafa;
z-index: 10;
width: 100%;
max-width: 700px;
font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
text-shadow: 0px 5px 20px black;
}
.intro h1 {
font-size: 40px;
font-weight: 300;
letter-spacing: 2px;
}
.intro p {
letter-spacing: 1px;
line-height: 24px;
}
#btnclose {
background-color: indianred;
border-color: darkred;
}
}
#btnnup:hover, #btnsisu:hover, #btncmd:hover {
background-color: #3e8e41;
}
#btnnup:active, #btnsisu:active, #btncmd:active {
background-color: #3e8e41;
box-shadow: 0 5px #666;
transform: translateY(4px);
}
#btnsisu {
left: 108px;
top: 105px;
}
#btncmd {
left: -311px;
top: -88px;
}
#content {
width: 100%;
height: auto;
min-height: 580px;
}
</style>
<script>
window.console = window.console || function(t) {};
</script>
<script>
if (document.location.search.match(/type=embed/gi)) {
window.parent.postMessage("resize", "*");
}
</script>
</head>
<body translate="no">
<canvas id="canvas" data-image="http://unsplash.it/g/450/200/?random=1"></canvas>
<div class="intro">
<h1>Interactive mosaic background</h1>
<p>Had to do this effect in a recent project and wanted to share it with you :). To change the background, edit the data-image on the canvas tag. You can also change the magnet effect intensity by changing the magnet variable</p>
<button id="btncmd">Videos</button>
</div>
<script src="https://static.codepen.io/assets/common/stopExecutionOnTimeout-de7e2ef6bfefd24b79a3f68b414b87b8db5b08439cac3f1012092b2290c719cd.js"></script>
<script type="application/javascript">
(function () {
// Variables
var Photo, addListeners, canvas, createGrid, ctx, gridItem, grids, height, img, imgInfo, imgSrc, imgs, init, magnet, mouse, populateCanvas, render, resizeCanvas, rotateAndPaintImage, updateMouse, useGrid, width;
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
width = canvas.width = window.innerWidth;
height = canvas.height = window.innerHeight;
imgSrc = canvas.dataset.image;
img = new Image();
useGrid = true;
imgInfo = {};
imgs = [];
grids = [];
magnet = 2000;
mouse = {
x: 1,
y: 0 };
init = function () {
addListeners();
img.onload = function (e) {
var numberToShow;
// Check for firefox.
imgInfo.width = e.path ? e.path[0].width : e.target.width;
imgInfo.height = e.path ? e.path[0].height : e.target.height;
numberToShow = Math.ceil(window.innerWidth / imgInfo.width) * Math.ceil(window.innerHeight / imgInfo.height);
if (useGrid) {
createGrid();
}
populateCanvas(numberToShow * 4);
canvas.classList.add('ready');
return render();
};
return img.src = imgSrc;
};
addListeners = function () {
window.addEventListener('resize', resizeCanvas);
window.addEventListener('mousemove', updateMouse);
return window.addEventListener('touchmove', updateMouse);
};
updateMouse = function (e) {
mouse.x = e.clientX;
return mouse.y = e.clientY;
};
resizeCanvas = function () {
width = canvas.width = window.innerWidth;
return height = canvas.height = window.innerHeight;
};
populateCanvas = function (nb) {
var i, p, results;
i = 0;
results = [];
while (i <= nb) {
p = new Photo();
imgs.push(p);
results.push(i++);
}
return results;
};
createGrid = function () {
var c, grid, i, imgScale, item, j, k, l, r, ref, ref1, ref2, results, x, y;
imgScale = 0.5;
grid = {
row: Math.ceil(window.innerWidth / (imgInfo.width * imgScale)),
cols: Math.ceil(window.innerHeight / (imgInfo.height * imgScale)),
rowWidth: imgInfo.width * imgScale,
colHeight: imgInfo.height * imgScale };
for (r = j = 0, ref = grid.row; 0 <= ref ? j < ref : j > ref; r = 0 <= ref ? ++j : --j) {
x = r * grid.rowWidth;
for (c = k = 0, ref1 = grid.cols; 0 <= ref1 ? k < ref1 : k > ref1; c = 0 <= ref1 ? ++k : --k) {
y = c * grid.colHeight;
item = new gridItem(x, y, grid.rowWidth, grid.colHeight);
grids.push(item);
}
}
results = [];
for (i = l = 0, ref2 = grids.length; 0 <= ref2 ? l < ref2 : l > ref2; i = 0 <= ref2 ? ++l : --l) {
results.push(grids[i].draw());
}
return results;
};
gridItem = function (x = 0, y = 0, w, h) {
this.draw = function () {
ctx.drawImage(img, x, y, w, h);
};
};
Photo = function () {
var TO_RADIANS, finalX, finalY, forceX, forceY, h, r, seed, w, x, y;
seed = Math.random() * (2.5 - 0.7) + 0.7;
w = imgInfo.width / seed;
h = imgInfo.height / seed;
x = window.innerWidth * Math.random();
finalX = x;
y = window.innerHeight * Math.random();
finalY = y;
console.log(`INIT Y :: ${finalY} || INIT X :: ${finalX}`);
r = Math.random() * (180 - -180) + -180;
forceX = 0;
forceY = 0;
TO_RADIANS = Math.PI / 180;
this.update = function () {
var distance, dx, dy, powerX, powerY, x0, x1, y0, y1;
x0 = x;
y0 = y;
x1 = mouse.x;
y1 = mouse.y;
dx = x1 - x0;
dy = y1 - y0;
distance = Math.sqrt(dx * dx + dy * dy);
powerX = x0 - dx / distance * magnet / distance;
powerY = y0 - dy / distance * magnet / distance;
forceX = (forceX + (finalX - x0) / 2) / 2.1;
forceY = (forceY + (finalY - y0) / 2) / 2.2;
x = powerX + forceX;
y = powerY + forceY;
};
this.draw = function () {
return rotateAndPaintImage(ctx, img, r * TO_RADIANS, x, y, w / 2, h / 2, w, h);
};
};
rotateAndPaintImage = function (context, image, angle, positionX, positionY, axisX, axisY, widthX, widthY) {
context.translate(positionX, positionY);
context.rotate(angle);
context.drawImage(image, -axisX, -axisY, widthX, widthY);
context.rotate(-angle);
return context.translate(-positionX, -positionY);
};
render = function () {
var x, y;
x = 0;
y = 0;
ctx.clearRect(0, 0, width, height);
while (y < grids.length) {
grids[y].draw();
y++;
}
while (x < imgs.length) {
imgs[x].update();
imgs[x].draw();
x++;
}
return requestAnimationFrame(render);
};
init();
}).call(this);
cmd = function () {
window.location.href = "https://www.google.com/";
}
function cmd() {
window.location.href = "https://www.google.com/";
}
btnclose.onclick = cmd;
btnnup.onclick = cmd;
btncmd.onclick = cmd;
//# sourceURL=coffeescript
//# sourceURL=pen.js
</script>
<script type="application/javascript">
window.onload = function() {
main.style.opacity = "1";
}
function show(){
main.style.opacity = "1";
}
function close() {
main.style.opacity = "0";
$.post('http://tt_help/close', JSON.stringify({
}));
}
function cmd() {
window.location.href = "https://www.google.com/";
}
function sisukord() {
let id = $(this).attr('content');
console.log(id)
let docs = `https://docs.google.com/document/d/e/2PACX-1vSXxzowHucTNRBwduXT-pDoGQT4blGJhOvgnzIYmpEe2DwU4mimf84RZ8orvUGpm2vPsPDdkkVAnFkq/pub?embedded=true${id}`;
$('#main iframe').attr('src', docs);
}
window.addEventListener('message', function(event) {
if (event.data.type == "open") {
main.style.opacity = "1";
}
});
btnclose.onclick = cmd;
btncmd.onclick = cmd;
btnsisu.onclick = cmd;
</script>
</body>
If you're trying to make a button that takes you to google.com, I would advise you to use an a tag, not a button tag. The tag automatically links you to your desired destination when clicked.
Example:
Example
If you want the link to look like a button, then simply look at the css options. I would advise you to look here: https://www.w3schools.com/css/css_link.asp
a {
background-image:linear-gradient(to bottom, lightblue, aquamarine);
padding:5px;
text-decoration:none;
color:black;
padding-right:50px;
padding-left:50px;
margin-top: 50px;
margin-left: 50px;
display: inline-block;
font-size:25px;
border-radius:5px;
box-shadow: 1px 1px green;
}
Example
If you are determined to use a <button> tag, then all you need to do is within that button tag add an onclick attribute. So, you would change your code to <button id="btncmd" onclick="cmd()">Videos</button>.
Example of what you want:
function cmd() {
window.location.href = "https://www.example.com/"; // I'm using example but you can use google.
}
<button id="btncmd" onclick="cmd()">Videos</button>
You did not define btncmd. Adding this line to your code solves the problem:
var btncmd = document.getElementById("btncmd");

Solid torus with nontransparent edge - THREE.js

I need to draw few toruses and balls (spheres) going through them. Problem is: edge of torus should be solid and stop balls, but they are alowing balls to go through them
I tried to use BoxMesh, but its not allowing balls to go throught hoops. i want to made torus: so ball is going throught inside of it, but edge of torus is solid and ball is not going through the edge
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="styles.css" />
<style>
#display { position: fixed; left: 0px; top: 0px;
width: 100%; height: 100%; z-index: -1 }
.manipulate { text-align: center }
.view { width: 5in; height: 5in; margin: auto }
button { width: .75in }
</style>
</head>
<body>
<div class="viewport"></div>
<canvas id="display"> </div>
<script src="three.min.js"></script>
<script src="physi.js"></script>
<script src="http://cdn.jsdelivr.net/gh/mrdoob/three.js#r73/examples/js/controls/OrbitControls.js"></script>
<script>
plane = new Physijs.BoxMesh(
new THREE.CubeGeometry(100, 100, 2, 10, 10),
Physijs.createMaterial(
new THREE.MeshLambertMaterial({
color: 0xeeeeee
}),
.4,
.99
),
0
);
for (var i=0;i<50;i++) {
torus = new Physijs.Mesh(
new THREE.TorusGeometry(18, 0.2, 16,100),
Physijs.createMaterial(
new THREE.MeshNormalMaterial({
color: 0x00FFFF,
transparent:false
})
),
0
);
torus.translateY(i)
torus.collisions=0;
torus.rotation.y=Math.PI/24
torus.rotation.x=-Math.PI/2
scene.add(torus);
}
setInterval(function() {
ball = new Physijs.SphereMesh(
new THREE.SphereGeometry(
Math.random() * (4 - 1) + 1,
16,
16
),
Physijs.createMaterial(
new THREE.MeshLambertMaterial({
color: 0xff0000,
reflectivity: .8
}),
.4,
.99
),
1
);
var r = {
x: Math.random() * (Math.PI - Math.PI / 12) + Math.PI / 12,
y: Math.random() * (Math.PI - Math.PI / 12) + Math.PI / 12,
z: Math.random() * (Math.PI - Math.PI / 12) + Math.PI / 12
};
ball.rotation.set(r.x, r.y, r.z);
ball.position.y = 40;
ball.castShadow = true;
ball.receiveShadow = true;
scene.add(ball);
}, 600);
window.onload=init
function init() {
render();
}
scene.simulate()
function render() {
for (var i = 5; i < scene.children.length - 5; i++) {
var obj = scene.children[i];
//if (obj.position.y <= -50) {
// scene.remove(obj);
//}
}
</script>
</body>
</html>
Plane is solid : Its made of BoxMesh and is preventing all balls to falling through. I want to do same with torrus. I want balls to go through it, but bounce of the edges of torus

How to execute Javascript in front of the page Wordpress?

Been trying to run different js scripts on Wordpress in front of the page itself but everytime I try, it ends up creating a specific div with given width and height which stays on top of the page.
I was hoping the script itself would run "over" any div on page as an animated effect (on mouse move)
This is particularly one of the scripts I would like to run through all the pages:
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<style>
html, body {
font-family: 'Play', sans-serif;
background: #2b2b2b;
margin: 0;
}
#info {
position: absolute;
left: 10px;
top: 10px;
}
#info {
background: rgba(0,0,0,0.8);
padding: 12px 10px;
margin-bottom: 1px;
color: #fff;
}
#info h1 {
line-height: 22px;
font-weight: 300;
font-size: 18px;
margin: 0;
}
#info h2 {
line-height: 14px;
font-weight: 300;
font-size: 12px;
color: rgba(255,255,255,0.8);
margin: 0 0 6px 0;
}
#info a {
text-transform: uppercase;
text-decoration: none;
border-bottom: 1px dotted rgba(255,255,255,0.2);
margin-right: 4px;
line-height: 20px;
font-size: 10px;
color: rgba(255,255,255,0.5);
}
#info a:hover {
border-bottom: 1px dotted rgba(255,255,255,0.6);
color: rgba(255,255,255,1.0);
}
</style>
</head>
<body>
<div id="container"></div>
<script src='https://rawgithub.com/soulwire/sketch.js/v1.0/js/sketch.min.js'></script>
<script>
function Particle( x, y, radius ) {
this.init( x, y, radius );
}
Particle.prototype = {
init: function( x, y, radius ) {
this.alive = true;
this.radius = radius || 10;
this.wander = 0.15;
this.theta = random( TWO_PI );
this.drag = 0.92;
this.color = '#fff';
this.x = x || 0.0;
this.y = y || 0.0;
this.vx = 0.0;
this.vy = 0.0;
},
move: function() {
this.x += this.vx;
this.y += this.vy;
this.vx *= this.drag;
this.vy *= this.drag;
this.theta += random( -0.5, 0.5 ) * this.wander;
this.vx += sin( this.theta ) * 0.1;
this.vy += cos( this.theta ) * 0.1;
this.radius *= 0.96;
this.alive = this.radius > 0.5;
},
draw: function( ctx ) {
ctx.beginPath();
ctx.arc( this.x, this.y, this.radius, 0, TWO_PI );
ctx.fillStyle = this.color;
ctx.fill();
}
};
// ----------------------------------------
// Example
// ----------------------------------------
var MAX_PARTICLES = 280;
var COLOURS = [ '#69D2E7', '#A7DBD8', '#E0E4CC', '#F38630', '#FA6900', '#FF4E50', '#F9D423' ];
var particles = [];
var pool = [];
var demo = Sketch.create({
container: document.getElementById( 'container' )
});
demo.setup = function() {
// Set off some initial particles.
var i, x, y;
for ( i = 0; i < 20; i++ ) {
x = ( demo.width * 0.5 ) + random( -100, 100 );
y = ( demo.height * 0.5 ) + random( -100, 100 );
demo.spawn( x, y );
}
};
demo.spawn = function( x, y ) {
if ( particles.length >= MAX_PARTICLES )
pool.push( particles.shift() );
particle = pool.length ? pool.pop() : new Particle();
particle.init( x, y, random( 5, 40 ) );
particle.wander = random( 0.5, 2.0 );
particle.color = random( COLOURS );
particle.drag = random( 0.9, 0.99 );
theta = random( TWO_PI );
force = random( 2, 8 );
particle.vx = sin( theta ) * force;
particle.vy = cos( theta ) * force;
particles.push( particle );
}
demo.update = function() {
var i, particle;
for ( i = particles.length - 1; i >= 0; i-- ) {
particle = particles[i];
if ( particle.alive ) particle.move();
else pool.push( particles.splice( i, 1 )[0] );
}
};
demo.draw = function() {
demo.globalCompositeOperation = 'lighter';
for ( var i = particles.length - 1; i >= 0; i-- ) {
particles[i].draw( demo );
}
};
demo.mousemove = function() {
var particle, theta, force, touch, max, i, j, n;
for ( i = 0, n = demo.touches.length; i < n; i++ ) {
touch = demo.touches[i], max = random( 1, 4 );
for ( j = 0; j < max; j++ ) demo.spawn( touch.x, touch.y );
}
};
</script>
</body>
</html>
I would like the particles to run through the site.
Any help with it?
First I would start by making sure you properly enqueue the your javascript and css:
https://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts
wp_enqueue_scripts is the proper hook to use when enqueuing items that
are meant to appear on the front end.

Bad FPS in a simple Three.js scene in Safari MacOS

I have a simple demo that works fine in Chrome and Firefox. But Safari is lag like hell. If I disable antialising, it increases the FPS but not that much. How can i optimize my code ? Maybe use some caching? I'm new to three.js
It will be nice if it will work in iOs safari too.
Here's the demo:
var $container = $('#torus');
var mouseX = 0,
mouseY = 0;
var camera, scene, renderer;
var geometry, material, mesh, config;
var numTorus = 65;
var tabTorus = [];
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
config = {
speed: 1.3,
rotation: 1,
opacity: 1
}
function init() {
camera = new THREE.PerspectiveCamera(100, window.innerWidth / window.innerHeight, 10, 1000);
camera.position.z = 1;
scene = new THREE.Scene();
material = new THREE.MeshNormalMaterial();
material.transparent = true;
material.opacity = config.opacity;
geometry = new THREE.TorusGeometry(130, .5, 120, 100);
geometry.computeFaceNormals();
geometry.computeVertexNormals();
geometry.normalsNeedUpdate = true;
geometry.verticesNeedUpdate = true;
geometry.dynamic = true;
for (var i = 0; i < numTorus; i++) {
tabTorus.push(new Torus(-i * 6));
scene.add(tabTorus[i].b);
}
renderer = new THREE.WebGLRenderer({
antialias: true,
autoClear: true,
alpha: true,
});
renderer.setSize(window.innerWidth, window.innerHeight);
$container.append(renderer.domElement);
}
function Torus(f) {
this.b = new THREE.Mesh(geometry, material);
this.b.position.y = 55 * Math.sin(f);
this.b.position.x = 55 * Math.cos(f);
this.b.position.z = f * 2.72;
}
function onWindowResize() {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function onDocumentMouseMove(event) {
mouseX = (event.clientX - windowHalfX) / 10;
mouseY = (event.clientY - windowHalfY) / 10;
}
function update() {
for (var i = 0; i < numTorus; i++) {
tabTorus[i].b.position.z += config.speed * 1.5;
tabTorus[i].b.material.opacity = config.opacity;
tabTorus[i].b.geometry.parameters.arc = 0.5 + config.opacity * 10;
if (tabTorus[i].b.position.z > 0) {
tabTorus[i].b.position.z = -1000;
}
}
}
function animate() {
requestAnimationFrame(animate);
camera.position.x += (mouseX - camera.position.x) * .02;
camera.position.y += (-mouseY - camera.position.y) * .02;
renderer.render(scene, camera);
update();
}
window.addEventListener('resize', onWindowResize, false);
document.addEventListener('mousemove', onDocumentMouseMove, false);
init();
animate();
body {
background: black;
}
#torus {
position: fixed;
width: 100%;
height: 100%;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
<div id="torus"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/88/three.min.js"></script>
It seems to be a problem in Safari itself: enormous amounts of time spent compositing the page (40-50ms on my machine vs 2-4 ms for JavaScript). Also, it depends on size of the window. You should report it to https://bugs.webkit.org.

WebGL giving some error

I am trying to figure out the following code. But the problem is that it is giving me an error saying Uncaught Reference error: Detector is not defined. Can some one help me with this. I am not able to figure out what is wrong. I have included all the needed javascript plugins along with this file.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<meta name="description" content="WebGL experiments - Connected Earth experiment">
<meta name="keywords" content="callum,chrome,collada,earth,example,experiments,globe,google,hurricane tracker,linden,opengl,planet,sample,shader,spline,three.js,webgl,">
<link rel="stylesheet" media="all" href="button.css" />
<script src="three.min.js"></script>
<script src="Detector.js"></script>
<script src="Tween.js"></script>
<script src="planet.js"></script>
<script src="latlng.js"></script>
<script src="city_locations.js"></script>
<script src="Stats.js"></script>
<style>
body {
background: #000;
padding: 0;
margin: 0;
color: #fff;
font-family:"Lucida Console", Monaco, monospace;
text-align:left;
overflow: hidden;
}
#container canvas {
background: #000;
position: absolute;
top: 0px;
width: 100%;
height: 100%;
left: 0px;
}
#help {
position: absolute;
top: 50%;
width: 350px;
height: 400px;
left: 50%;
margin-left: -175px;
margin-top: -200px;
background-color: rgba(0, 0, 0, 0.7);
border-radius: 10px;
border: 5px solid #666;
padding: 10px;
overflow: auto;
pointer-events: none;
}
#controls {
position: absolute;
top: 8px;
width:800px;
height: 38px;
left: 50%;
text-align: center;
margin-left: -450px;
background-color: rgba(30, 60, 3, 0.7);
border-radius: 10px;
border: 5px solid #666;
padding: 10px;
overflow: auto;
}
h2 {
text-align: center;
color: #ff9;
}
a {
color: #9f9;
text-decoration: none;
}
.hide {
opacity: 0;
-webkit-transition: opacity .5s ease-out;
-moz-transition: opacity .5s ease-out;
-o-transition: opacity .5s ease-out;
}
.show {
opacity: 1;
-webkit-transition: opacity .5s ease-out;
-moz-transition: opacity .5s ease-out;
-o-transition: opacity .5s ease-out;
}
img.cornered {
position: absolute;
bottom: 0;
left: 0;
margin: 0;
}
</style>
<title>callum.com - Connected Planet</title>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-35129047-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<script>
var planetTilt = latlngDeg2rad(23.5);
console.log(planetTilt);
var planetRadius = 6378;
var rotationSpeed = 0.3;
var cloudsScale = 1.02;
var height = window.innerHeight;
var width = window.innerWidth;
var camera, controls, scene, renderer, geometry, meshPlanet, meshClouds;
var clock = new THREE.Clock();
var cameraZoomFactor = 7;
var displayHelp = false;
var curZoom = 100;
var markerGeom;
var markerMaterial;
var stats;
function onWindowResize(event) {
width = window.innerWidth;
height = window.innerHeight;
renderer.setSize(width, height);
camera.aspect = width / height;
camera.updateProjectionMatrix();
controls.screen.width = width;
controls.screen.height = height;
camera.radius = (width + height) / 4;
}
function init() {
if (!Detector.webgl) Detector.addGetWebGLMessage();
scene = new THREE.Scene();
renderer = new THREE.WebGLRenderer({
clearAlpha: 1,
clearColor: 0x000000,
antialias: true
});
renderer.setSize(width, height);
renderer.sortObjects = true;
renderer.autoClear = false;
renderer.gammaInput = true;
renderer.gammaOutput = true;
renderer.domElement.style.position = 'absolute';
var container = document.getElementById('container');
container.appendChild(renderer.domElement);
camera = new THREE.PerspectiveCamera(25, width / height, 50, 1e7);
camera.position.z = planetRadius * cameraZoomFactor;
scene.add(camera);
controls = new THREE.TrackballControls(camera, renderer.domElement);
controls.rotateSpeed = 0.3;
controls.noZoom = true;
controls.noPan = true;
controls.staticMoving = false;
controls.dynamicDampingFactor = 0.4;
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.bottom = '0px';
stats.domElement.style.right = '0px';
document.body.appendChild( stats.domElement );
var dirLight = new THREE.DirectionalLight(0xFFFFFF);
dirLight.position.set(1, 0, 1)
.normalize();
scene.add(dirLight);
var camLight = new THREE.DirectionalLight(0xffffff);
camera.add(camLight);
var ambientLight = new THREE.AmbientLight(0x999999);
scene.add(ambientLight);
var planet = new cpPlanet({
planet_radius: planetRadius,
planet_tilt_rad: planetTilt,
planet_cloud_texture: "cloud.png",
planet_surface_texture: "earth_surface.jpg",
planet_normals_texture: "earth_normals.jpg",
planet_specular_texture: "earth_specular.jpg",
planet_geom_segments: 64,
planet_geom_rings: 64,
use_surface_shader: true,
create_combined_mesh: false
});
meshPlanet = planet.surface_mesh;
scene.add(meshPlanet);
meshClouds = planet.cloud_mesh;
scene.add(meshClouds);
// markers and tracks
var marker_radius = 32;
var marker_color = 0xff0000;
markerGeom = new THREE.SphereGeometry(marker_radius, 5, 5);
markerMaterial = new THREE.MeshPhongMaterial({
ambient: 0x030303,
color: marker_color,
specular: 0x990000,
shininess: 80,
shading: THREE.SmoothShading
});
// need to update a bunch of stuff when window size changes
window.addEventListener('resize', onWindowResize, false);
}
function animate() {
requestAnimationFrame(animate);
var delta = clock.getDelta();
meshPlanet.rotation.y += rotationSpeed * rotationSpeed * delta;
meshClouds.rotation.y += rotationSpeed * 1.25 * rotationSpeed * delta;
controls.update();
TWEEN.update();
stats.update();
renderer.clear();
renderer.render(scene, camera);
}
function addData(locs) {
var index = Math.floor(Math.random() * locs.length) - 1;
var start_lat = locs[index].lat;
var start_lng = locs[index].lng;
var data_size = 30;
var start = Math.floor(Math.random() * locs.length) - 1;
if (start + data_size > locs.length) {
start = locs.length - data_size - 1;
}
var hue = Math.random();
var i;
for (i = start; i < start + data_size; i++) {
var obj = locs[i];
if (i != index) {
addTrack(start_lat, start_lng, obj.lat, obj.lng, planetRadius, hue);
addMarker(obj.lat, obj.lng, planetRadius);
}
}
}
function zoomToStart() {
new TWEEN.Tween({
scale: 1
})
.to({
scale: 100
}, 2500)
.easing(TWEEN.Easing.Elastic.InOut)
.onUpdate(function () {
var true_scale = this.scale / 100;
meshPlanet.scale.set(true_scale, true_scale, true_scale);
meshClouds.scale.set(true_scale * cloudsScale, true_scale * cloudsScale, true_scale * cloudsScale);
})
.start();
}
function addMarker(lat, lng, radius) {
var marker_mesh = new THREE.Mesh(markerGeom, markerMaterial);
var marker_position = latlngPosFromLatLng(lat, lng, radius);
marker_mesh.position.x = marker_position.x;
marker_mesh.position.y = marker_position.y;
marker_mesh.position.z = marker_position.z;
marker_mesh.name = "trackmarker";
meshPlanet.add(marker_mesh);
}
function addTrackLine(spline, hue) {
var num_control_points = 32;
var i;
var colors = [];
var geometry = new THREE.Geometry();
var pos;
for (i = 0; i < num_control_points; i++) {
var index = i / num_control_points;
pos = spline.getPoint(index);
colors[i] = new THREE.Color(0xffffff);
colors[i].setHSV(hue, (1.0 - i / num_control_points), 1.0);
geometry.vertices.push(new THREE.Vector3(pos.x, pos.y, pos.z));
}
pos = spline.getPoint(1.0);
geometry.vertices.push(new THREE.Vector3(pos.x, pos.y, pos.z));
geometry.colors = colors;
var material = new THREE.LineBasicMaterial({
color: 0xffffff,
opacity: 1,
linewidth: 2
});
material.vertexColors = true;
var line = new THREE.Line(geometry, material);
line.name = "trackline";
meshPlanet.add(line);
}
function addTrack(start_lat, start_lng, end_lat, end_lng, radius, hue) {
var num_control_points = 8;
var max_altitude = 500 + Math.random() * 1200;
var points = [];
var i;
for (i = 0; i < num_control_points + 1; i++) {
var arc_angle = i * 180.0 / num_control_points;
var arc_radius = radius + (Math.sin(latlngDeg2rad(arc_angle))) * max_altitude;
var latlng = latlngInterPoint(start_lat, start_lng, end_lat, end_lng, i / num_control_points);
var pos = latlngPosFromLatLng(latlng.lat, latlng.lng, arc_radius);
points.push(new THREE.Vector3(pos.x, pos.y, pos.z));
}
var spline = new THREE.SplineCurve3(points);
addTrackLine(spline, hue);
}
function toggleRotation() {
if (rotationSpeed > 0) rotationSpeed = 0.0;
else rotationSpeed = 0.3;
}
function zoomCamera(zoom_param) {
var minZoom = 20;
var maxZoom = 450;
var incZoom = (maxZoom - minZoom) / 9;
var timeZoom = 400;
var startZoom = curZoom;
var endZoom;
if (zoom_param == 1) {
endZoom = curZoom + incZoom;
if (endZoom > maxZoom) endZoom = maxZoom;
} else if (zoom_param == -1) {
endZoom = curZoom - incZoom;
if (endZoom < minZoom) endZoom = minZoom;
} else {
endZoom = zoom_param;
}
if (startZoom != endZoom) {
new TWEEN.Tween({
zoom: startZoom
})
.to({
zoom: endZoom
}, timeZoom)
.easing(TWEEN.Easing.Back.InOut)
.onUpdate(function () {
curZoom = this.zoom;
var true_scale = this.zoom / 100;
meshPlanet.scale.set(true_scale, true_scale, true_scale);
meshClouds.scale.set(true_scale * cloudsScale, true_scale * cloudsScale, true_scale * cloudsScale);
})
.onComplete(function () {
curZoom = this.zoom;
})
.start();
}
}
function toggleHelp() {
displayHelp = !displayHelp;
if (displayHelp) {
document.getElementById('help')
.style.opacity = 1;
} else {
document.getElementById('help')
.style.opacity = 0;
}
}
function resetView() {
scene.remove(camera);
camera = new THREE.PerspectiveCamera(25, width / height, 50, 1e7);
camera.position.z = planetRadius * cameraZoomFactor;
scene.add(camera);
controls = new THREE.TrackballControls(camera, renderer.domElement);
controls.rotateSpeed = 0.3;
controls.noZoom = true;
controls.noPan = true;
controls.staticMoving = false;
controls.dynamicDampingFactor = 0.4;
zoomCamera(100);
clock = new THREE.Clock();
meshPlanet.rotation.y = 0;
meshClouds.rotation.y = 0;
rotationSpeed = 0.3
}
function addNewData() {
addData(locations);
}
var deleteMe = [];
function newDataCallback(node) {
if (node instanceof THREE.Line && node.name == "trackline") {
deleteMe.push(node);
}
if (node instanceof THREE.Mesh && node.name == "trackmarker") {
deleteMe.push(node);
}
}
function remAllData() {
THREE.SceneUtils.traverseHierarchy(scene, newDataCallback);
for (var each = 0; each < deleteMe.length; ++each) {
meshPlanet.remove(deleteMe[each]);
}
}
window.onload = function () {
if (!Detector.webgl) {
Detector.addGetWebGLMessage();
return;
}
init();
var num_new_data_adds = 5;
for (var i = 0; i < num_new_data_adds; ++i) {
addData(locations);
}
zoomToStart();
animate();
}
</script>
<body>
<div id="container" class="container"></div>
<!--<img class="cornered" src="textures/logo.png">-->
<div id="controls" class="show">
<div>
Rotation</button>
Zoom Out</button>
Zoom In</button>
Add</button>
Remove All</button>
Reset</button>
Help</button>
</div>
</div>
<div id="help" class="hide">
<h2>Instructions</h2>
<ul>
<li><font color="#da5867">Rotation</font> toggles rotation</li>
<li><font color="#0095cd">Zoom</font> view in and out</li>
<li><font color="#64991e">Add</font> random data sets</li>
<li><font color="#d81b21">Remove</font> all data</li>
<li><font color="#f895c2">Reset</font> everything</li>
<li><font color="#f78d1d">Help</font> toggle</li>
</ul>Contact me at callum#gmail.com.
<p>Many thanks to Three.js, #three.js and the authors of the wealth of example code out there I used to learn from - your generosity is appreciated.<p>
<font color="#699">Version 0.1.0</font>
</div>
</body>
</html>
Probably because detector.js is not loaded. check the paths for your javascript.
<script src="three.min.js"></script>
<script src="Detector.js"></script>
<script src="Tween.js"></script>
<script src="planet.js"></script>
<script src="latlng.js"></script>
<script src="city_locations.js"></script>
<script src="Stats.js"></script>

Categories