D3 pan+ zoom constraints - svg

I'm trying to zoomable/draggle rectangle from going outside of the svg bounds when panning and zooming. I've tried to implement it based off of this example, but i cant seem to get it to work. I've created this jsfiddle with just the rectangle that is zoomable and draggable. Again, im trying to make it so that you can not drag the rectangle outside of the svg box i put the border on. I know i need to update the move function. the code below is from the first link example but it does not seem to work well so i commented part of it out.
function move() {
var t = d3.event.translate,
s = d3.event.scale;
//t[0] = Math.min(width / 2 * (s - 1), Math.max(width / 2 * (1 - s), t[0]));
//t[1] = Math.min(height / 2 * (s - 1) + 230 * s, Math.max(height / 2 * (1 - s) - 230 * s, t[1]));
//zoom.translate(t);
svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}
Edit: So additionally i need to be able to drag the rectangle when you are zoomed in all the way and its bigger than the svg. In the image below, the blue rectangle is the svg and green would be the rectangle and you are zoomed in all the way so that the green rectangle takes up the much more than the SVG. This is similar to the map in the constrained zoom example. You can zoom into the states and drag across the country, navigating to states outside the current svg size

You can do this by constraining the translation coordinates you set to the size of the box:
var t = d3.event.translate,
s = d3.event.scale;
t[0] = Math.max(0, Math.min(t[0], width - s*50));
t[1] = Math.max(0, Math.min(t[1], height - s*50));
svg.attr("transform", "translate(" + t + ")scale(" + d3.event.scale + ")");
This is constraining the x coordinate to be between 0 and the width minus however much space is required to show the box completely -- this depends on the zoom level and the term therefore contains s. For the y coordinate, it is exactly the same.
This is much easier if you don't use both a translation and explicit coordinate settings through x and y for the box -- to offset from the top left corner, simply set an initial translation.
Complete example here.

Related

Is there a way to transform a point in the initial photo coordinates after a crop with cropperjs

I use cropperjs to crop some image, I keep in database the result of getData method who return values in white on the picture.
{x, y, width, height, rotate}
My users can place points on the cropped image in the red space, is there a way to retrieve the coordinates of the point in the blue space?
The crop ratio is free so there is no relation between original image ratio and crop ratio and I don't have the original image size.
Thank you for your help
At first get coordinates in bounding box
bbx = redx + x
bby = redy + y
Now make rotation about bounding box center
bluex = bbcenterx + (bbx - bbcenterx) * Cos(rotate) + (bby - bbcentery) * Sin(rotate)
bluey = bbcentery - (bbx - bbcenterx) * Sin(rotate) + (bby - bbcentery) * Cos(rotate)
If you don't know bounding box size, but know initial picture width w and height h, you can calculate bounding box center
bbcenterx = (w * Abs(Sin(rotate)) + h * Abs(Cos(rotate))) / 2
bbcenterx = (w * Abs(Cos(rotate)) + h * Abs(Sin(rotate))) / 2

How to create a bar chart made up of very small squares

I am trying to use d3 to create a chart which will end up being almost like a bar chart. However, I would like to accomplish this by using very small individual squares. Something like the image below but ignoring the random squares dotted around:
http://i.imgur.com/jYSyhur.jpg
Each square represents a vote (or group of votes depending on how many votes are made on a given day) and can have 3 possible values, each with a different shade of blue, i.e. light blue, blue and dark blue.
One example I have already found is http://bost.ocks.org/mike/miserables/ but I would like to convert this style in to a bar chart.
I have already attempted at doing the markup in HTML using tables and divs, but this got widely out of control and ending up massively slowing down the page loading speed -- hence the use of SVG instead.
Any ideas on how to approach this would be appreciated.
The basis for what you want to do is the stacked bar chart: http://bl.ocks.org/mbostock/3886208
However, there are a few things you will need to take into account. The y and x axes must be proportional so you will have to carefully consider:
the size of the graph
the number of data points
the max value each data point can have
and select a height, width and "value" for each tick - each square.
I've made a demonstration fiddle here: http://jsfiddle.net/sa5RK/
It assumes a few things (for simplicity!):
Each tick is one value
The height & width of the box is set
var boxheight = 6;
the height / width can be dynamic based on the size of the box and data values
var margin = {top: 20, right: 20, bottom: 80, left: 40},
width = boxheight * data.length;
var max = d3.max(data, function(d){return d.a + d.b + d.c});
var height = max * boxheight;
I hope that's enough to get you started!
The other key thing which will help you out, is learning how each data joined selection can be set to a variable, then selecting inside of it will allow you access to the outside bound data. eg. below, each data group (value in the original array) -> has types (a,b or c) -> has rectangles
var groups = svg.selectAll(".group")
.data(data)
.enter().append("g")
.attr("transform", function(d,i){return "translate(" + x(i) + ", 0)"})
.attr("class", "group")
var types = groups.selectAll(".type")
.data(function(d){return d.offsets})
.enter().append("g")
.attr("transform", function(d){ return translate(0,y(d.y1))})
.attr("class", "type")
.attr("fill", function(d){return color(d.type)})
types.selectAll("rect")
.data(function(d){return d3.range(0,d.value)})
.enter().append("rect")
.attr("height", boxheight-0.5)
.attr("width", boxheight-0.5)
.attr("y", function(d){ return boxheight * d })

Issues with bullet entry points for "shoulder mounted" guns

I'm making a SHMUP game that has a space ship. That space ship currently fires a main cannon from its center point. The sprite that represents the ship has a center based registration point. 0,0 is center of the ship.
When I fire the main cannon i make a bullet and assign make its x & y coordinates match the avatar and add it to the display list. This works fine.
I then made two new functions called fireLeftCannon, fireRightCannon. These create a bullet and add it to the display list but the x, y values are this.y + 15 and this.y +(-) 10. This creates a sort of triangle of bullet entry points.
Similar to this:
   ▲
▲   ▲
the game tick function will adjust the avatar's rotation to always point at the cursor. This is my aiming method. When I shoot straight up all 3 bullets fire up in the expected pattern. However when i rotate and face the right the entry points do not rotate. This is not an issue for the center point main cannon.
My question is how do i use the current center position ( this.x, this.y ) and adjust them based on my current rotation to place a new bullet so that it is angled correctly.
Thanks a lot in advance.
Tyler
EDIT
OK i tried your solution and it didn't work. Here is my bullet move code:
var pi:Number = Math.PI
var _xSpeed:Number = Math.cos((_rotation - 90) * (pi/180) );
var _ySpeed:Number = Math.sin((_rotation - 90) * (pi / 180) );
this.x += (_xSpeed * _bulletSpeed );
this.y += (_ySpeed * _bulletSpeed );
And i tried adding your code to the left shoulder cannon:
_bullet.x = this.x + Math.cos( StaticMath.ToRad(this.rotation) ) * ( this.x - 10 ) - Math.sin( StaticMath.ToRad(this.rotation)) * ( this.x - 10 );
_bullet.y = this.y + Math.sin( StaticMath.ToRad(this.rotation)) * ( this.y + 15 ) + Math.cos( StaticMath.ToRad(this.rotation)) * ( this.y + 15 );
This is placing the shots a good deal away from the ship and sometimes off screen.
How am i messing up the translation code?
What you need to start with is, to be precise, the coordinates of your cannons in the ship's coordinate system (or “frame of reference”). This is like what you have now but starting from 0, not the ship's position, so they would be something like:
(0, 0) -- center
(10, 15) -- left shoulder
(-10, 15) -- right shoulder
Then what you need to do is transform those coordinates into the coordinate system of the world/scene; this is the same kind of thing your graphics library is doing to draw the sprite.
In your particular case, the intervening transformations are
world ←translation→ ship position ←rotation→ ship positioned and rotated
So given that you have coordinates in the third frame (how the ship's sprite is drawn), you need to apply the rotation, and then apply the translation, at which point you're in the first frame. There are two approaches to this: one is matrix arithmetic, and the other is performing the transformations individually.
For this case, it is simpler to skip the matrices unless you already have a matrix library handy already, in which case you should use it — calculate "ship's coordinate transformation matrix" once per frame and then use it for all bullets etc.
I'll now explain doing it directly.
The general method of applying a rotation to coordinates (in two dimensions) is this (where (x1,y1) is the original point and (x2,y2) is the new point):
x2 = cos(angle)*x1 - sin(angle)*y1
y2 = sin(angle)*x1 + cos(angle)*y1
Whether this is a clockwise or counterclockwise rotation will depend on the “handedness” of your coordinate system; just try it both ways (+angle and -angle) until you have the right result. Don't forget to use the appropriate units (radians or degrees, but most likely radians) for your angles given the trig functions you have.
Now, you need to apply the translation. I'll continue using the same names, so (x3,y3) is the rotated-and-translated point. (dx,dy) is what we're translating by.
x3 = dx + x2
y3 = dy + x2
As you can see, that's very simple; you could easily combine it with the rotation formulas.
I have described transformations in general. In the particular case of the ship bullets, it works out to this in particular:
bulletX = shipPosX + cos(shipAngle)*gunX - sin(shipAngle)*gunY
bulletY = shipPosY + sin(shipAngle)*gunX + cos(shipAngle)*gunY
If your bullets are turning the wrong direction, negate the angle.
If you want to establish a direction-dependent initial velocity for your bullets (e.g. always-firing-forward guns) then you just apply the rotation but not the translation to the velocity (gunVelX, gunVelY).
bulletVelX = cos(shipAngle)*gunVelX - sin(shipAngle)*gunVelY
bulletVelY = sin(shipAngle)*gunVelX + cos(shipAngle)*gunVelY
If you were to use vector and matrix math, you would be doing all the same calculations as here, but they would be bundled up in single objects rather than pairs of x's and y's and four trig functions. It can greatly simplify your code:
shipTransform = translate(shipX, shipY)*rotate(shipAngle)
bulletPos = shipTransform*gunPos
I've given the explicit formulas because knowing how the bare arithmetic works is useful to the conceptual understanding.
Response to edit:
In the code you edited into your question, you are adding what I assume is the ship position into the coordinates you multiply by sin/cos. Don't do that — just multiply the offset of the gun position from the ship center by sin/cos and only then add that to the ship position. Also, you are using x x; y y on the two lines, where you should be using x y; x y. Here is your code edited to fix those two things:
_bullet.x = this.x + Math.cos( StaticMath.ToRad(this.rotation)) * (-10) - Math.sin( StaticMath.ToRad(this.rotation)) * (+15);
_bullet.y = this.y + Math.sin( StaticMath.ToRad(this.rotation)) * (-10) + Math.cos( StaticMath.ToRad(this.rotation)) * (+15);
This is the code for a gun at offset (-10, 15).

Bezier curve through three points

I have read similar topics in order to find solution, but with no success.
What I'm trying to do is make the tool same as can be found in CorelDraw, named "Pen Tool". I did it by connecting Bezier cubic curves, but still missing one feature, which is dragging curve (not control point) in order to edit its shape.
I can successfully determine the "t" parameter on the curve where dragging should begin, but don't know how to recalculate control points of that curve.
Here I want to higlight some things related to CorelDraw''s PenTool behaviour that may be used as constaints. I've noticed that when dragging curve strictly vertically, or horizontally, control points of that Bezier curve behave accordingly, i.e. they move on their verticals, or horizontals, respectively.
So, how can I recalculate positions of control points while curve dragging?
Ive just look into Inkspace sources and found such code, may be it help you:
// Magic Bezier Drag Equations follow!
// "weight" describes how the influence of the drag should be distributed
// among the handles; 0 = front handle only, 1 = back handle only.
double weight, t = _t;
if (t <= 1.0 / 6.0) weight = 0;
else if (t <= 0.5) weight = (pow((6 * t - 1) / 2.0, 3)) / 2;
else if (t <= 5.0 / 6.0) weight = (1 - pow((6 * (1-t) - 1) / 2.0, 3)) / 2 + 0.5;
else weight = 1;
Geom::Point delta = new_pos - position();
Geom::Point offset0 = ((1-weight)/(3*t*(1-t)*(1-t))) * delta;
Geom::Point offset1 = (weight/(3*t*t*(1-t))) * delta;
first->front()->move(first->front()->position() + offset0);
second->back()->move(second->back()->position() + offset1);
In you case "first->front()" and "second->back()" would mean two control points
The bezier curve is nothing more then two polynomials: X(t), Y(t).
The cubic one:
x = ax*t^3 + bx*t^2 + cx*t + dx
0 <= t <= 1
y = ay*t^3 + by*t^2 + cy*t + dy
So if you have a curve - you have the poly coefficients. If you move your point and you know it's t parameter - then you can simply recalculate the poly's coefficients - it will be a system of 6 linear equations for coefficients (for each of the point). The system is subdivided per two systems (x and y) and can be solved exactly or using some numerical methods - they are not hard too.
So your task now is to calculate control points of your curve when you know the explicit equation of your curve.
It can be also brought to the linear system. I don't know how to do it for generalized Bezier curve, but it is not hard for cubic or quadric curves.
The cubic curve via control points:
B(t) = (1-t)^3*P0 + 3(1-t)^2*t*P1 + 3(1-t)*t^2*P2 + t^3*P3
Everything you have to do is to produce the standard polynomial form (just open the brackets) and to equate the coefficients. That will provide the final system for control points!
When you clicks on curve, you already know position of current control point. So you can calculate offset X and offset Y from that point to mouse position. In case of mouse move, you would be able to recalculate new control point with help of X/Y offsets.
Sorry for my english

Normalized Device Coordinates to window coordinates

I just read some stuff about the theory behind 3d graphics. As I understand it, normalized device coordinates (NDC) are coordinates that describe a point in the interval from -1 to 1 on both the horizontal and vertical axis. On the other hand window coordinates describe a point somewhere between (0,0) and (width,height) of the window.
So my formula to convert a point from the NDC coordinate system to the window system would be
xwin = width + xndc * 0.5 * width
ywin = height + ynfv * 0.5 * height
The problem now is that in the OpenGL documentation for glViewport there is an other formula:
xwin = ( xndc + 1 ) * width * 0.5 + x
ywin = ( yndc + 1 ) * height * 0.5 + y
Now I'm wondering what I am getting wrong. Especially I'm wondering what the additional "x" and "y" mean.
Hope the question isn't too "not programming related", but I thought somehow it is related to graphics programming.
Viewport doesn't necessarily start at (0; 0), so 'x' and 'y' in OpenGL documentation refers to viewport starting position.
To see what's wrong with your equation, try transforming (0; 0) normalized position, and you will get (width; height) instead of (width / 2; height / 2).

Resources