// set the scene size
var WIDTH = 800;
var HEIGHT = 640;
// set some camera attributes
var VIEW_ANGLE = 45,
ASPECT = WIDTH / HEIGHT,
NEAR = 0.1,
FAR = 10000;
var $container = $('#container');
// create a WebGL renderer, camera
var renderer = new THREE.WebGLRenderer();
var camera = new THREE.PerspectiveCamera(VIEW_ANGLE,
ASPECT,
NEAR,
FAR);
var scene = new THREE.Scene();
// the camera starts at 0,0,0 so pull it back
camera.position.z = 1000;
// start the renderer
renderer.setSize(WIDTH, HEIGHT);
// attach the render-supplied DOM element
$container.append(renderer.domElement);
// create the sphere's material
var sphereMaterial = new THREE.MeshLambertMaterial({
color: 0xCC0000
});
// set up the sphere vars
var radius = 50, segments = 16, rings = 16;
// create a new mesh with sphere geometry -
// we will cover the sphereMaterial next!
var sphere = new THREE.Mesh(
new THREE.SphereGeometry(radius, segments, rings),
sphereMaterial);
sphere.position.x = 20;
sphere.doubleSided = true;
// add the sphere to the scene
scene.add(sphere);
// and the camera
scene.add(camera);
/* Light it up */
var pointLight = new THREE.PointLight(0xFFFFFF);
pointLight.position.x = 10;
pointLight.position.y = 50;
pointLight.position.z = 130;
scene.add(pointLight);
window.setInterval(update, 16.66666666);
var keyboard = new THREEx.KeyboardState();
function update() {
if (keyboard.pressed("W")) {
camera.position.z -= 5;
} else if (keyboard.pressed("S")) {
camera.position.z += 5;
}
renderer.render(scene, camera);
}
That is my code, a simple demow here using W and S keys makes me go zoom in/out a 3D Sphere.
However, when I get "inside" the sphere, I can't see it's back face, even though I put sphere.doubleSided = true;.
I tried putting renderer.setFaceCulling(true); (and false too), but none of them fixed it.
Any ideas?
use side: THREE.DoubleSide in material
which version of three.js are you using ?
jsfiddle
Related
It seems that if a display object has a perspective projection applied to it, calling localToGlobal gives you the wrong coordinates. In the following code, I draw a rectangle, rotate it slightly about its X axis, then draw an oval inside it using coordinates derived from localToGlobal. It works fine, until I try to apply a perspective projection, then the coordinates are all wrong. Anyone know how to get around this problem?
var w:uint = 300, h:uint = 150;
var s:Sprite = new Sprite();
s.graphics.beginFill(0x000000);
s.graphics.drawRect(-w/2,0,w,h);
s.graphics.endFill();
s.x = 275; s.y = 200; s.z = 600;
s.rotationX = -45;
addChild(s);
var point00:Point = new Point(0,0);
var point0h:Point = new Point(0,h);
var midL:Point = new Point(-w/2,h/2);
var midR:Point = new Point(w/2,h/2);
/*var VP:PerspectiveProjection = new PerspectiveProjection();
VP.fieldOfView = 55;
var p:Point = new Point(275,100);
VP.projectionCenter = p;
s.transform.perspectiveProjection = VP;*/
var o:Shape = new Shape();
o.graphics.beginFill(0x00ff00);
o.graphics.drawEllipse(
s.localToGlobal(midL).x,
s.localToGlobal(point00).y,
s.localToGlobal(midR).x - s.localToGlobal(midL).x,
s.localToGlobal(point0h).y - s.localToGlobal(point00).y
);
addChild(o);
It seems that setting perspectiveProjection does not force the player to redraw the object, and localToGlobal depends on redraw for correct results. You can wait 1 tick like you found (setTimeout for 0ms or enterFrame for 1 frame will do it) or you can force the player to redraw using BitmapData/draw():
// ...
s.transform.perspectiveProjection = VP;
new BitmapData(1, 1).draw(s); // forces player to redraw the sprite
var o:Shape = new Shape();
o.graphics.beginFill(0x00ff00);
o.graphics.drawEllipse(
s.localToGlobal(midL).x,
s.localToGlobal(point00).y,
s.localToGlobal(midR).x - s.localToGlobal(midL).x,
s.localToGlobal(point0h).y - s.localToGlobal(point00).y
);
addChild(o);
I found a workaround that isn't terrible. All you have to do is put a slight delay before the localToGlobal calls and then they will return the right coordinates. That also fixes local3DToGlobal.
I have this code for a message to appear on stage when player finishes drag and drop. I would like this sprite to be removed when a button is clicked for the next frame. Can someone help me with the code?
stage.addEventListener(Event.ENTER_FRAME, EntFrame);
function EntFrame (e:Event):void
{
if (CntP1+CntP2+CntP3+CntP4+CntP5+CntP6+CntP7+CntP8 == 40)
{
var w:int = 400, h:int = 200;
var win:Sprite = new Sprite();
win.name = "Mywin";
addChild(win);
// draw rounded rect with subtle vertical linear gradient fill and blue stroke
win.graphics.lineStyle(4,0x0077ff);
var mat:Matrix = new Matrix();
mat.createGradientBox(w, h, 90 * (Math.PI / 180));
win.graphics.beginGradientFill(GradientType.LINEAR,[0xffffff,0xeeeeee],[1.00,1.00],[0,255],mat);
win.graphics.drawRoundRect(0,0,w,h,15,15);
// show center "YOU WIN!" text
var tf:TextField = new TextField();
tf.autoSize = TextFieldAutoSize.LEFT;
tf.antiAliasType = AntiAliasType.ADVANCED;
tf.defaultTextFormat = new TextFormat("Arial, Verdana",36,0x454545,true);
tf.text = "Κέρδισες!";
tf.selectable = false;
win.addChild(tf);
tf.x = w/2 - tf.width/2;
tf.y = h/2 - tf.height/2;
// add a drop shadow
var dropShadow:DropShadowFilter = new DropShadowFilter(3,45,0,.35,8,8,1,3);
win.filters = [dropShadow];
// center the graphic
win.x = stage.stageWidth/2 - win.width/2;
win.y = stage.stageHeight/2 - win.height/2;
}
}
Your code isn't written well and needs rewriting to ensure reuse or scalability of your project, but here's a quick way out.
make a holder Sprite, something like
var messageHolder:Sprite = new Sprite();
addChild(messageHolder);
add all the messages to that holder in any fashion you like. When you need to erase the contents of that holder, call following method:
function clearHolderContents(holder:DisplayObjectContainer):void
{
if (holder.numChildren < 1)
return; // no need to continue this method if the target is empty
for (var i:int = holder.numChildren - 1; i >= 0; i--)
removeChild(holder.getChildAt(i));
}
This method can clear contents of any DisplayObjectContainer => use it for your messageHolder:
clearHolderContents(messageHolder);
Hope that helps!
I'd like to use a hitArea to capture click events in my EaselJS project, but the hitArea Shape I've assigned doesn't seem to be respected.
jsFiddle Example
var stage = new createjs.Stage($("#game")[0]);
// This will be a big button
var container = new createjs.Container();
stage.addChild(container);
// This defines the hit area of the button
var hitArea = new createjs.Shape();
var hitAreaGraphics = hitArea.graphics;
// A 1x1 black square, centered about the origin
hitAreaGraphics.beginFill("#000").drawRect(-0.5, -0.5, 1, 1).endFill();
// Assign the hitArea
container.hitArea = hitArea;
// container.addChild(hitArea);
container.onTick = function() {
var canvas = container.getStage().canvas;
container.x = canvas.width / 2;
container.y = canvas.height / 2;
container.scaleX = canvas.width;
container.scaleY = canvas.height;
};
container.onPress = function() {
alert("Eureka!");
};
// Run the simulation
updater = {
tick: function() { stage.update(); }
};
createjs.Ticker.addListener(updater);
If I add the hitArea shape as a child of the container object, the click events work fine.
I've modified a page where I can drag and drop images onto a canvas. It does everything I want except for one. I've tried multiple methods (including scripts, e.g. Kinetic and Raphael, which I still think may be the route to go) but have dead ended:
Once the image is dropped, I can't drag it on the canvas to a new position.
function drag(e)
{
//store the position of the mouse relativly to the image position
e.dataTransfer.setData("mouse_position_x",e.clientX - e.target.offsetLeft );
e.dataTransfer.setData("mouse_position_y",e.clientY - e.target.offsetTop );
e.dataTransfer.setData("image_id",e.target.id);
}
function drop(e)
{
e.preventDefault();
var image = document.getElementById( e.dataTransfer.getData("image_id") );
var mouse_position_x = e.dataTransfer.getData("mouse_position_x");
var mouse_position_y = e.dataTransfer.getData("mouse_position_y");
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
// the image is drawn on the canvas at the position of the mouse when we lifted the mouse button
ctx.drawImage( image , e.clientX - canvas.offsetLeft - mouse_position_x , e.clientY - canvas.offsetTop - mouse_position_y );
}
function convertCanvasToImage() {
var canvas = document.getElementById('canvas');
var image_src = canvas.toDataURL("image/png");
window.open(image_src);
}
Here is a JSFiddle that I used as my initial start point - http://fiddle.jshell.net/gael/GF96n/4/ (drag the JSFiddle logo onto the canvas and then try to move it). I've since added CSS, tabs, content, etc. to my almost working page. The function I don't want to lose is the ability to drag the single image multiple times (clone) onto the canvas.
Any ideas/examples/pointers on how to create this functionality?
You need to do a couple of changes to your code, instead of drawing the image immediately to the canvas, you need to keep track of all images dropped. imagesOnCanvas will be filled with all images dropped.
var imagesOnCanvas = [];
function drop(e)
{
e.preventDefault();
var image = document.getElementById( e.dataTransfer.getData("image_id") );
var mouse_position_x = e.dataTransfer.getData("mouse_position_x");
var mouse_position_y = e.dataTransfer.getData("mouse_position_y");
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
imagesOnCanvas.push({
context: ctx,
image: image,
x:e.clientX - canvas.offsetLeft - mouse_position_x,
y:e.clientY - canvas.offsetTop - mouse_position_y,
width: image.offsetWidth,
height: image.offsetHeight
});
}
You also need an animation loop, which will go through all images in imagesOnCanvas and draw them sequentially. requestAnimationFrame is used to achieve this.
function renderScene() {
requestAnimationFrame(renderScene);
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.clearRect(0,0,
canvas.width,
canvas.height
);
for(var x = 0,len = imagesOnCanvas.length; x < len; x++) {
var obj = imagesOnCanvas[x];
obj.context.drawImage(obj.image,obj.x,obj.y);
}
}
requestAnimationFrame(renderScene);
Next you will have to monitor mousedown events on canvas, and if the event occurs on an image the startMove action can be called
canvas.onmousedown = function(e) {
var downX = e.offsetX,downY = e.offsetY;
// scan images on canvas to determine if event hit an object
for(var x = 0,len = imagesOnCanvas.length; x < len; x++) {
var obj = imagesOnCanvas[x];
if(!isPointInRange(downX,downY,obj)) {
continue;
}
startMove(obj,downX,downY);
break;
}
}
The isPointInRange function returns true if the mouse event occurred on an image object
function isPointInRange(x,y,obj) {
return !(x < obj.x ||
x > obj.x + obj.width ||
y < obj.y ||
y > obj.y + obj.height);
}
Once 'move mode' is active, the x/y coordinates of the object are changed to reflect the new mouse position
function startMove(obj,downX,downY) {
var canvas = document.getElementById('canvas');
var origX = obj.x, origY = obj.y;
canvas.onmousemove = function(e) {
var moveX = e.offsetX, moveY = e.offsetY;
var diffX = moveX-downX, diffY = moveY-downY;
obj.x = origX+diffX;
obj.y = origY+diffY;
}
canvas.onmouseup = function() {
// stop moving
canvas.onmousemove = function(){};
}
}
Working example here:
http://jsfiddle.net/XU2a3/41/
I know it's been like 2 years, but I'll give it a try... In the answer provided by #lostsource, the dataTransfer object is not supported in Opera browser, and the jsfiddle is not working. I desperately need that answer, that's what I've been looking for, but it's not working!
There are some threads about textures which do not showing up. I have tried them all, but nothing helped.
I have spent a few hours on this now. Every time I end up looking at a black sphere.
I am working on Chrome v18 and Windows 7. I also tried Firefox, but this browser does not really support Three.js.
This is the body of the script:
<body>
<script src="../build/Three.js"></script>
<script src="js/Stats.js"></script>
<script src="../build/jquery-1.7.2.min.js"></script>
This is the script itself:
// stap1) camera, set the scene size
var WIDTH = 400,
HEIGHT = 300;
// set some camera attributes
var VIEW_ANGLE = 45,
ASPECT = WIDTH / HEIGHT,
NEAR = 0.1,
FAR = 10000;
var camera = new THREE.PerspectiveCamera(
VIEW_ANGLE,
ASPECT,
NEAR,
FAR );
// stap2) scene:
var scene = new THREE.Scene();
// the camera starts at 0,0,0 so pull it back
scene.add(camera);
camera.position.z = +300;
// get the DOM element to attach to
// - assume we've got jQuery to hand
var container = $('#container');
// stap3)create a WebGL renderer:
var renderer = new THREE.WebGLRenderer();
// start the renderer
renderer.setSize(WIDTH, HEIGHT);
// attach the render-supplied DOM element
container.append(renderer.domElement);
// bol maken:
// create the sphere's material
// b.v: THREE.MeshBasicMaterial
var sphereMaterial = new THREE.MeshLambertMaterial(
{
map: THREE.ImageUtils.loadTexture("http://dev.root.nl/tree/examples/textures/ash_uvgrid01.jpg")
});
// set up the sphere vars
var radius = 50, segments = 16, rings = 16;
var sphereGeometry = new THREE.SphereGeometry(radius, segments, rings);
// create a new mesh with sphere geometry -
var sphere = new THREE.Mesh(
sphereGeometry,
sphereMaterial
);
sphere.position.x=0;
var s=1;
sphere.scale.set(s, s, s);
// add the sphere to the scene
scene.add(sphere);
// create a point light
var pointLight = new THREE.PointLight( 0xFFFFFF );
// set its position
pointLight.position.x = 10;
pointLight.position.y = 50;
pointLight.position.z = 130;
// add to the scene
scene.add(pointLight);
// draw!
renderer.render(scene, camera);
You need to wait until the image used as texture is fully downloaded.
I have put your code on the web: http://jsfiddle.net/4Qg7K/ and just added a classic "render loop":
requestAnimationFrame(render);
function render(){
requestAnimationFrame(render);
sphere.rotation.y += 0.005; //rotation stuff, just for fun
renderer.render(scene, camera);
};
requestAnimationFrame function works like a timer, calling to the render function each time the browser is ready to update the web page.
BTW, Three.js works fine with Firefox.