Initial Sprite Size in Three.js - javascript

Can someone help me understand how three.js initially determines the size/scale of a sprite?
At the moment I'm working with 4 sprites (PNGs with transparency that are 3000px × 1830px) stacked in 3D space, but I'm having to scale them up between 16x and 22x. In order to keep the sprites from looking squashed, though, I have to scale the y-axis 75% of the x-scale.
Eventually, I want to be able to pull in images systematically, and have them scale appropriately.
It's possible I just haven't set this thing up correctly. It looks right, but it's super hacky-feeling right now. I pretty much changed a bunch of numbers, until it looked right to me. I don't like that. I want to understand.
Here's what I'm working with currently:
http://valorink.com/3d-test/stackoverflow/

Looking into the code of the Sprite class reveals that a simple plane with width and height of 1 is created in the constructor. I wouldn't have expected anything else, because the geometry size is usually not defined by the texture size.
You probably want them to fill the viewport, so you have to scale them. With perspective camera its a bit of math, because the amount of x-scale (or y-scale) to fit the viewport size relates to the distance to the camera. So, it should be something like
var halfHeigt = distanceToCamera / Math.tan( camera.fov/2 * Math.PI / 180 );
y-scale = halfHeight * 2;
And of course you need to consider the aspect ratio in order to not looking squashed. So, x-scale should be y-scale * textureWidth / textureHeight, or the other way round y-scale = x-scale * textureHeight / textureWidth.

Related

How to get the position of object in Three.js relative to the camera to draw a trail?

I have an object (a pen) in my scene, which is rotating around its axis in the render loop.
groupPen.rotation.y += speed;
groupPen.rotation.x += speed;
and I have also a TrackballControls, which allows the user to rotate the whole scene.
What I now want is to get the "real" position of the pen (or its pick) and place small spheres to create a trail behind it.
This means I need to know where the camera is looking at and place the trail spheres behind the peak of the pen and exclude them from the animation and the TrackballControls.
What I tried is:
groupSphereTrail.lookAt(camera.position);
didn't work. Means no reaction at all.
camera.add(groupSphereTrail);
didn't work. groupSphereTrail is than not in the view area, couldn't make it visible - manipulating position.z didn't help.
Then I tried something like sending a tray with traycaster. The idea was to send a ray from the center of the camera through the peak of the pen and then draw the trail there. But then I still doesn't have the "real" position.
Another idea was to create a 2d vector of the current position of the pen peak and just draw an html element on top of the canvas:
var p = penPeak.position.clone();
var vector = p.project(camera);
vector.x = (vector.x + 1) / 2 * width;
vector.y = -(vector.y - 1) / 2 * height;
but this also doesn't work.
What could be another working solution?
Current progress:
https://zhaw.swissmade.xyz
(click on the cap of the pen to see the writing - this writing trail should stay at its place when you rotate the camera)
If i understood the question right, you want to show the trail as if it were draw on the screen itself (screen space)?
yourTrailParticle.position.project(camera)
camera.add(yourTrailParticle)
That's the basic idea, but it gets a bit tricky with PerspectiveCamera. You could set up a whole new THREE.Scene to hold the trail, and render it with a fixed size orthographic camera.
The point is .project() will give you a normalized screen space coordinate of a world space vector, and you need to keep it somehow in sync with that camera (since the screen is too). The perspective camera has distortion so you need to figure out the appropriate distance to map the coordinate to. With a separate scene, this may become easier.

CreateJS - scaling the canvas does not scale the mouse coordinates

I am working on a big project where exercises in Canvas are created through JSON-data and CreateJS. The purpose of having it in HTML 5 is to not have to use a separate app for your phone, you can always use the website.
Everything works fine, however in mobile the Canvas is rescaled to full screen. This is done through checking the screen size, and if it's small enough to be mobile the canvas is scaled through this code:
// browser viewport size
var w = window.innerWidth;
var h = window.innerHeight;
// stage dimensions
var ow = canvasWidth;
var oh = canvasHeight;
// keep aspect ratio
var scale = Math.min(w / ow, h / oh);
stage.scaleX = scale;
stage.scaleY = scale;
// adjust canvas size
stage.canvas.width = ow * scale;
stage.canvas.height = oh * scale;
This works great for most of the exercises, like quizzes and such, where all you have to do is click on a button. However we also have some drag and drop-exercises, and an exercise where you can color a drawing. These of course rely on the mouse coordinates to work properly. The problem is, when the canvas is scaled the mouse coordinates are not. So when you drag an item or try to draw, there is an offset happening. So your drawing appears way left of your click, and when picking up a draggable object it doesn't quite follow your click correctly.
Had I made the code from the beginning I'm fairly sure how I would have recalculated the coordinates, but since they are calculated by CreateJS I don't really know how I should go about this.
This was reported as a problem by someone about a year ago here, where this solution was suggested:
I was able to work around this by adding a top-level container and attaching my Bitmaps to that and scaling it.
The whole exercise is inside a container which I have tried to scale but to no avail. I have also tried sending the scale as a parameter to the parts of the exercise created (for example the menu, background images and such) and not scale it all together, and it seems to work okay since then I can exclude the drawing layer. But since it is a large project and many different exercises and parts to be scaled it would take quite some time to implement, and I'm not sure it's a viable solution.
Is there a good and easy way to rescale the mouse coordinates along with the canvas size in CreateJS? I have found pure Javascript examples here on SO, but nothing for CreateJS in particular.
Continued searching and finally stumbled upon this, which I hadn't seen before:
EaselJS - dragging children of scaled parent. It was exactly what I was looking for. I needed to change the coordinates I drew with this:
var coords = e.target.globalToLocal(e.stageX, e.stageY);
Then I could use the coords.x and coords.y instead of directly using e.stageX and e.stageY like before.

Using KineticJs to update and rescale a drawing

I am having an issue trying to update a drawing that uses a number of different drawing objects. The drawing is similar to an AutoCad drawing and is measured in mm so the scale is already being calculated in order to get the drawing to fit on the stage. When this is calculated the scale is set to one.
I have the drawing objects (lines, circles, arcs, etc.) stored in an array. I am trying to update the drawing andd rescale it without clearing the stage and doing a full redraw to improve performance.
What I am trying to do is to increment the length of the drawing. The drawing has a cut point so the objects to the right of the cut point will move by the increment value and any lines that span the cut point will increase in length. This change will require an update to the scale initially calculated to get the drawing to appear on the stage.
There are 2 Fiddles that I have set up to demonstrate the problem. The first (http://jsfiddle.net/tctruckscience/3HxuP/4/) shows what I am currently doing. The problem is that drawing will scale but it will start to move away from the right hand side of the screen.
originalRectWidth = 2600;
rectWidth = rectWidth + 20;
scaleValue = originalRectWidth / rectWidth;
oldRectWidth = rect.getWidth();
newPixelsPerScaleUnit = 260 / rectWidth;
newRectScaled = rectWidth * newPixelsPerScaleUnit;
drawingGroup.setWidth(newRectScaled);
rect.setWidth(newRectScaled);
drawingGroup.scaleBy(scaleValue);
Also, if I make a lot of increments and then make a large decrement using a text box there is an issue in the redraw. It that lines are not decremented correctly. I think it is an issue with the scaling. When I resize the page, which calls a refresh of the drawing objects from the array in which they are held, the drawing proportions are correct
The second Fiddle (http://jsfiddle.net/tctruckscience/rsEyA/15) shows how I would like the drawing to behave.
oldWidth = drawingGroup.getWidth();
newWidth = drawingGroup.getWidth() + 20;
scaleValue = originalWidth / newWidth;
Is there a way to do this?

Canvas image scaling, rotating, drawing

For a game project, I'm drawing images using their properties such as fileName, position, scale, rotation.
Here is the part that does the drawing:
this.context.save();
this.context.translate(item.position.x, item.position.y);
if (item.rotation > 0) {
this.context.rotate(item.rotation * (Math.PI / 180));
}
if (item.scale.x !== 1 || item.scale.y !== 1) {
this.context.scale(item.scale.x, item.scale.y);
}
var width = item.imageSize.width * item.scale.x;
var height = item.imageSize.height * item.scale.y;
this.context.drawImage(this.assets.image[item.fileName], -(width / 2), -(height / 2), width, height);
this.context.restore();
(don't mind the strange positioning, it's not important)
This works fine, but there is one thing that I don't understand:
Rotation and scaling can be done in two different ways: first scale and then rotate, or other way around. Logically, one would think that first scale then rotation is correct, but for some reason, it only works correctly if I first rotate then scale.
What is the correct way of doing this?
Where is your point of origin for your objects? Are the x/y the top left? If so that could be causing the issue.
Demo Scaling Then Rotating
ctx.translate(box.x, box.y);
ctx.scale(2,2);
ctx.rotate(box.angle);
Demo Rotating Then Scaling
ctx.translate(box.x, box.y);
ctx.rotate(box.angle);
ctx.scale(2,2);
If you notice both of those demos work fine regardless of when I perform the scaling and rotating. My point of origins however (where I translate to) are in the center of the boxes.
To answer your question (or attempt to) there is no right or wrong way, you can scale first or rotate first, its really just a matter of preference.
The "correct way" really depends on what you're trying to do. For you, it seems like rotating and then scaling results in what you expect.
Here is a fiddle that shows the difference between rotating then scaling and scaling then rotating: http://jsfiddle.net/HYbC7/3/
What's unexpected for me is when you scale then rotate. If you scale(x, y) where x and y are not equal, then rotate, then the rotation along the x-axis will be different than the rotation along the y-axis and the resulting grid will be skewed.

Calculate new width when skewing in canvas

I'm using canvas for a project and I have a number of elements that I'm skewing. I'm only skewing on the y value and just want to know what the new width of the image is after skewing (so I can align it with another canvas element). Check out the code below to see what I mean
ctx.save();
//skew the context
ctx.transform(1,0,1.3,0,0,0);
//draw two images with different heights/widths
ctx.drawImage(image,0,0,42,60);
ctx.drawImage(image,0,0,32,25);
The goal would be to know that the 42 by 60 image was now a X by 60 image so I could do some translating before drawing it at 0,0. It's easy enough to measure each image individually, but I have different skew values and heights/widths throughout the project that need to be align. Currently I use this code (works decently for images between 25 and 42 widths):
var skewModifier = imageWidth*(8/6)+(19/3);
var skewAmount = 1.3; //this is dynamic in my app
var width = (skewModifier*skewAmount)+imageWidth;
As images get wider though this formula quickly falls apart (I think it's a sloping formula not a straight value like this one). Any ideas on what canvas does for skews?
You should be able to derive it mathematically. I believe:
Math.atan(skewAmount) is the angle, in radians, that something is skewed with respect to the origin.
So 1.3 would skew the object by 0.915 radians or 52 degrees.
So here's a red unskewed object next to the same object skewed (painted green). So you have a right triangle:
We know the origin angle (0.915 rads) and we know the adjacent side length, which is 60 and 25 for your two images. (red's height).
The hypotenuse is the long side thats being skewed.
And the opposite side is the triangle bottom - how much its been skewed!
Tangent gets us opposite / adjacent if I recall, so for the first one:
tan(0.915) = opposite / 60, solving for the opposite in JavaScript code we have:
opposite = Math.tan(0.915)*60
So the bottom side of the skewed object starts about 77 pixels away from the origin. Lets check our work in the canvas:
http://jsfiddle.net/LBzUt/
Looks good to me!
The triangle in question of course is the canvas origin, that black dot I painted, and the bottom-left of the red rectangle, which is the original position that we're searching for before skewing.
That was a bit of a haphazard explanation. Any questions?
Taking Simon's fiddle example one step further, so you can simply enter the degrees:
Here's the fiddle
http://jsfiddle.net/LBzUt/33/

Categories