Is there a way to get two parallel lines that won't change the distance in Paper js? - paperjs

I need to draw two parallel lines that won't change the distance between them regardless of the inclination of the lines.
I think one possibility is by changing the start point of the line B to form a perpendicular line with the line A but I can't find a way to get the coordinates of the start or end point of a line using Path.Line

Here is a sketch that should help you reach your goal.
const createParallelLines = (start, end, distance) => {
const line = end - start;
const leftStart = start + line.rotate(90).normalize(distance / 2);
const leftEnd = end + line.rotate(90).normalize(distance / 2);
const rightStart = start + line.rotate(-90).normalize(distance / 2);
const rightEnd = end + line.rotate(-90).normalize(distance / 2);
const leftLine = new Path.Line(leftStart, leftEnd);
const rightLine = new Path.Line(rightStart, rightEnd);
return [leftLine, rightLine];
};
const [leftLine, rightLine] = createParallelLines(view.center - 100, view.center + 100, 20);
leftLine.selected = true;
rightLine.selected = true;

Related

QCustomPlot vertical line at axis

I am working QCustomPlot with Qt and need to change the color of a particular vertical grid line within the graph please let us know how we can change that I attached the image of my requirement.
The bleo code solve the issue
GraphTesting(QCustomPlot * customPlot)
{
// generate some data:
QVector<double> x(101), y(101); // initialize with entries 0..100
for (int i = 0; i < 101; ++i)
{
x[i] = i; //i / 50.0 - 1; // x goes from -1 to 1
y[i] = x[i]/2; // let's plot a quadratic function
}
// create graph and assign data to it:
customPlot->addGraph();
customPlot->graph(0)->setData(x, y);
// give the axes some labels:
customPlot->xAxis->setLabel("x");
customPlot->yAxis->setLabel("y");
customPlot->rescaleAxes();
QCPItemLine *step = new QCPItemLine(customPlot);
step->setPen(QPen(QColor(140, 0, 0)));
double begin = 25;
double first = customPlot->yAxis->range().lower;
double end = customPlot->yAxis->range().upper; //example values
step->start->setCoords(begin, first);
step->end->setCoords(begin, end);
customPlot->replot();
}

How to translate a vector from an offset vector

How to translate a vector from an offset vector.
I have a line with 2 points attached one on the line start and one on the end vector of the line.
I want to translate the line and the points base on the DragConstrols position and not base on the line position I am just updating the line geometry vertices and the points position base on the line start and end vectors.
Keap in mind the points are not childs of the line, all objects are childs of the Scene
The line stores the points inside the userData of the line.
My goal is to translate all this 3 objects from the drag offset Vector3
Here is the screenshots of the line with the points.
start_vector = (-140, 60, 0)
end_vector = (-70, 100, 0)
I know the line start vector before the user drags the line v1 = (-140, 60, 0) and I
know the line end vector before the drag v2 = (-70, 100, 0)
Now when the user drags the line with the DragConstrols I dont let the dragControls to change the line position I get the dragConstrol vector3 and I want to translate the line vetrices base on that vector.
The DragControls allways start from (0, 0, 0) so I try to add the line vectors (v1, v2) with the position but I get this result.
Can someone show me how to set the line start and end vector from the dragControls position.
Or how to translate vectors from offset vectors.
Thank you.
My code so far.
Keep in mind the line is a Line2 (fat line) three/examples/jsm/lines/Line2
class NewLine extends Line2 {
private _start = new Vector3();
private _end = new Vector3();
/** The viewport width */
public viewportWidth: number;
/** The viewport height */
public viewportHeight: number;
/** The line3 */
public line3 = new Line3();
public get start() { return this._start; }
public set start(v: Vector3) {
this._start = v;
this.line3.set(v, this._end);
this.geometry['setPositions']([
v.x,
v.y,
v.z,
this._end.x,
this._end.y,
this._end.z
]);
this.geometry['verticesNeedUpdate'] = true; // maybe i don't need that
this.geometry.computeBoundingSphere();
this.computeLineDistances();
}
public get end() { return this._end; }
public set end(v: Vector3) {
this._end = v;
this.line3.set(this._start, v);
this.geometry['setPositions']([
this._start.x,
this._start.y,
this._start.z,
v.x,
v.y,
v.z,
]);
this.geometry['verticesNeedUpdate'] = true; // maybe i don't need that
this.geometry.computeBoundingSphere();
this.computeLineDistances();
}
constructor( start: Vector3, end: Vector3 ) {
super();
// create geometry
const geometry = new LineGeometry();
geometry.setPositions([
start.x, start.y, start.z,
end.x, end.y, end.z
]);
this.geometry = geometry;
// create material
const material = new LineMaterial({
color: 0x000000,
linewidth:5,
depthTest: false, // new
vertexColors: false,
});
this.material = material;
this.computeLineDistances();
this.scale.set( 1, 1, 1 );
this.line3.set(start, end);
}
}
/**
* Translates a line base on DragControls position.
* line: The NewLine
* position: The new Vector3 position from dragControls
*/
translateLineFromVector(line: NewLine, position: Vector3) {
const v1 = line.start;
const v2 = line.end;
const offset_start = line.start.clone().add( position ).sub(line.position);
const offset_end = line.end.clone().add( position ).sub(line.position);
line.start.copy( offset_start );
line.end.copy( offset_end );
}
Standard approach for dragging:
On mouse down(X,Y):
If Clicked at object and not Dragging:
Dragging = True
X0 = X
Y0 = Y
//important - remember object coordinates at this moment!
V1_0 = V1
V2_0 = V2
On mouse moving (X,Y) :
If Dragging:
//Draw object at coordinates shifted by (X - X0), (Y - Y0)
//from initial position, not from the current one
V1.X = V1_0.X + X - X0
V1.Y = V1_0.Y + Y - Y0
same for V2
DrawObject(V1,V2)
On Mouse Up(X,Y):
If Dragging:
Fragging = False
Fix positions V1,V2 if needed

Create a point in a direction In Cesiumjs

I am using CesiumJs. I would like to create point D at distance C from point A using the direction B
Point A => start Position (CartographicPosition {latitude, longitude; altitude})
Direction B => direction from A (HeadingPitchRoll {heading, pitch, roll})
Distance C => in meters
I am trying to get the rotation an object is facing, and create a point in front of him.
My current implementation is
public createROIfromRotation(position: Cartographic, rotation: HeadingPitchRoll): Cartographic {
const pos = Cesium.Ellipsoid.WGS84.cartographicToCartesian(position);
const quat = Cesium.Transforms.headingPitchRollQuaternion(pos, rotation);
const rot = CesiumMath.QuaternionToEuler(quat);
const dir = Cesium.Cartesian3.multiplyByScalar(rot, 10, new Cesium.Cartesian3());
const roiPos = Cesium.Cartesian3.add(pos, dir, new Cesium.Cartesian3());
return Cesium.Ellipsoid.WGS84.cartesianToCartographic(roiPos);
}
But it is not rotating around the object, it is doing some kind of curve in different planes.
I would like the red point to be always in front of the truck at 10 meters distance
Exemple
I fixed using
public createROIfromRotation(position: Cartographic, rotation: HeadingPitchRoll) {
const cartesianPosition = Cesium.Ellipsoid.WGS84.cartographicToCartesian(position);
rotation.heading = rotation.heading - CesiumMath.deg2Rad(90);
const referenceFrame1 = Cesium.Transforms.headingPitchRollQuaternion(cartesianPosition, rotation);
const rotationMatrix = Cesium.Matrix3.fromQuaternion(referenceFrame1, new Cesium.Matrix3());
// Replace 1000 for changing the distance
const rotationScaled = Cesium.Matrix3.multiplyByVector(rotationMatrix, new Cesium.Cartesian3(10000, 0, 0), new Cesium.Cartesian3());
const roiPos = Cesium.Cartesian3.add(cartesianPosition, rotationScaled, new Cesium.Cartesian3());
this.store$.dispatch(new ROIsStoreActions.CreateROIPoint({position: Cesium.Ellipsoid.WGS84.cartesianToCartographic(roiPos), id: uuid()}));
}
So basically, converting everything to Matrix3 before applying my calculations

Rotate point from a given center in Flex

I'm trying to rotate a point in my Canvas from a given point (center). In my MouseDown handler, I save the point where user click (oldPos), and in my MouseMove handler, I'm doing this:
private function onMouseMove(event:MouseEvent):void
{
// Where the user pointer right now
var endPoint:Point = new Point(event.localX,event.localY);
// Calculate angle in radians from the user pointer
var angle:Number = getLineAngleFromHorizontal(oldPos,endPoint);
var rad:Number = Math.PI * (angle / 180);
// Point which I want to rotate
pTop = new Point(oldPos.x,oldPos.y - 30);
var distance:Number = Point.distance(oldPos,pTop);
// Calculate the translation point from previously distance and angle
var translatePoint:Point = Point.polar(distance, rad);
// New point coordinates (in theory)
pTop.x += translatePoint.x;
pTop.y += translatePoint.y;
// Then, draw the line...
}
Where getLineAngleFromHorizontal is a function that returns the angle formed by a center and a give point:
private function getLineAngleFromHorizontal(p1:Point,p2:Point):Number
{
var RotVecOrigen:Point = new Point((p2.x-p1.x),(p2.y-p1.y));
var ModRot:Number = Math.sqrt((RotVecOrigen.x*RotVecOrigen.x)+(RotVecOrigen.y*RotVecOrigen.y));
var ret:Number;
if(((RotVecOrigen.x < 0) && (RotVecOrigen.y <= 0))||((RotVecOrigen.x >= 0) && (RotVecOrigen.y < 0)))
{
ret = Math.round((180.0*(Math.acos(RotVecOrigen.x/ModRot))/Math.PI));
}else{
ret = Math.round((180.0*(-Math.acos(RotVecOrigen.x/ModRot))/Math.PI));
}
return ret;
}
To see an example, watch the image below:
But I don't know why isn't work. I mean, pTop point isn't move where I want, and I think that my calcs are correct.
Can anybody help me? (maybe someone with Math knowledge)
I'm not entirely sure what you want to accomplish. Do you want your new point to be at an 330 degree offset from your center point?
If you want to move your point 330 degrees, use this:
function directionalDistance($start:Point, $direction:Number, $distance:Number, $zeroDegreesUp:Boolean = false):Point{
if($zeroDegreesUp) $direction = ( $direction + 270)%360;
var x:Number = Math.cos($direction * Math.PI / 180) * $distance;
var y:Number = Math.sin($direction * Math.PI / 180) * $distance;
return new Point($start.x +x, $start.y + y);
}
//
var newPoint:Point = directionalDistance(new Point(event.localX,event.localY), 330, 50, true);

How to draw a continuous curved line from 3 given points at a time

I am trying to draw a continuous curved line in flash. There are many methods but none of the ones I have found so far quite fit my requirements. First of all, I want to use the flash graphic api's curveTo() method. I DO NOT want to simulate a curve with hundreds of calls to lineTo() per curved line segment. It is my experience and understanding that line segments are processor heavy. Flash's quadratic bezier curve should take less CPU power. Please challenge this assumption if you think I am wrong.
I also do not want to use a pre-made method that takes the entire line as an argument (eg mx.charts.chartClasses.GraphicsUtilities.drawPolyline()).
The reason is that I will need to modify the logic eventually to add decorations to the line I am drawing, so I need something I understand at its lowest level.
I have currently created a method that will draw a curve given 3 points, using the mid-point method found here.
Here is a picture:
The problem is that the lines do not actually curve through the "real" points of the line (the gray circles). Is there a way using the power of math that I can adjust the control point so that the curve will actually pass through the "real" point? Given only the current point and its prev/next point as arguments? The code to duplicate the above picture follows. It would be great if I could modify it to meet this requirement (note the exception for first and last point).
package {
import flash.display.Shape;
import flash.display.Sprite;
import flash.display.Stage;
import flash.geom.Point;
[SWF(width="200",height="200")]
public class TestCurves extends Sprite {
public function TestCurves() {
stage.scaleMode = "noScale";
var points:Array = [
new Point(10, 10),
new Point(80, 80),
new Point(80, 160),
new Point(20, 160),
new Point(20, 200),
new Point(200, 100)
];
graphics.lineStyle(2, 0xFF0000);
var point:Point = points[0];
var nextPoint:Point = points[1];
SplineMethod.drawSpline(graphics, point, null, nextPoint);
var prevPoint:Point = point;
var n:int = points.length;
var i:int;
for (i = 2; i < n + 1; i++) {
point = nextPoint;
nextPoint = points[i]; //will eval to null when i == n
SplineMethod.drawSpline(graphics, point, prevPoint, nextPoint);
prevPoint = point;
}
//straight lines and vertices for comparison
graphics.lineStyle(2, 0xC0C0C0, 0.5);
graphics.drawCircle(points[0].x, points[0].y, 4);
for (i = 1; i < n; i++) {
graphics.moveTo(points[i - 1].x, points[i - 1].y);
graphics.lineTo(points[i].x, points[i].y);
graphics.drawCircle(points[i].x, points[i].y, 4);
}
}
}
}
import flash.display.Graphics;
import flash.geom.Point;
internal class SplineMethod {
public static function drawSpline(target:Graphics, p:Point, prev:Point=null, next:Point=null):void {
if (!prev && !next) {
return; //cannot draw a 1-dimensional line, ie a line requires at least two points
}
var mPrev:Point; //mid-point of the previous point and the target point
var mNext:Point; //mid-point of the next point and the target point
if (prev) {
mPrev = new Point((p.x + prev.x) / 2, (p.y + prev.y) / 2);
}
if (next) {
mNext = new Point((p.x + next.x) / 2, (p.y + next.y) / 2);
if (!prev) {
//This is the first line point, only draw to the next point's mid-point
target.moveTo(p.x, p.y);
target.lineTo(mNext.x, mNext.y);
return;
}
} else {
//This is the last line point, finish drawing from the previous mid-point
target.moveTo(mPrev.x, mPrev.y);
target.lineTo(p.x, p.y);
return;
}
//draw from mid-point to mid-point with the target point being the control point.
//Note, the line will unfortunately not pass through the actual vertex... I want to solve this
target.moveTo(mPrev.x, mPrev.y);
target.curveTo(p.x, p.y, mNext.x, mNext.y);
}
}
Later I will be adding arrows and things to the draw method.
I think you're looking for a Catmull-Rom spline. I've googled an AS3 implementation for you but haven't tried it so use at your own discretion:
http://actionsnippet.com/?p=1031
Ok, the Catmull-Rom spline suggestion is a good one but not exactly what I am looking for.
The example from the link provided was a good starting point, but a bit inflexible. I have taken it and modified my original source code to use it. I am posting this as an answer because I think it is more modular and easier to understand than Zevan's blog post (no offense Zevan!). The following code will display the following image:
Here is the code:
package {
import flash.display.Shape;
import flash.display.Sprite;
import flash.display.Stage;
import flash.geom.Point;
[SWF(width="300",height="300")]
public class TestCurves extends Sprite {
public function TestCurves() {
stage.scaleMode = "noScale";
//draw a helpful grid
graphics.lineStyle(1, 0xC0C0C0, 0.5);
for (var x:int = 0; x <= 300; x += 10) {
graphics.moveTo(x, 0);
graphics.lineTo(x, 300);
graphics.moveTo(0, x);
graphics.lineTo(300, x);
}
var points:Array = [
new Point(40, 20),
new Point(120, 80),
new Point(120, 160),
new Point(60, 160),
new Point(60, 200),
new Point(240, 150),
new Point(230, 220),
new Point(230, 280)
];
SplineMethod.setResolution(5);
graphics.lineStyle(2, 0xF00000);
graphics.moveTo(points[0].x, points[0].y);
var n:int = points.length;
var i:int;
for (i = 0; i < n - 1; i++) {
SplineMethod.drawSpline(
graphics,
points[i], //segment start
points[i + 1], //segment end
points[i - 1], //previous point (may be null)
points[i + 2] //next point (may be null)
);
}
//straight lines and vertices for comparison
graphics.lineStyle(2, 0x808080, 0.5);
graphics.drawCircle(points[0].x, points[0].y, 4);
for (i = 1; i < n; i++) {
graphics.moveTo(points[i - 1].x, points[i - 1].y);
graphics.lineTo(points[i].x, points[i].y);
graphics.drawCircle(points[i].x, points[i].y, 4);
}
}
}
}
import flash.display.Graphics;
import flash.geom.Point;
internal class SplineMethod {
//default setting will just draw a straight line
private static var hermiteValues:Array = [0, 0, 1, 0];
public static function setResolution(value:int):void {
var resolution:Number = 1 / value;
hermiteValues = [];
for (var t:Number = resolution; t <= 1; t += resolution) {
var h00:Number = (1 + 2 * t) * (1 - t) * (1 - t);
var h10:Number = t * (1 - t) * (1 - t);
var h01:Number = t * t * (3 - 2 * t);
var h11:Number = t * t * (t - 1);
hermiteValues.push(h00, h10, h01, h11);
}
}
public static function drawSpline(target:Graphics, segmentStart:Point, segmentEnd:Point, prevSegmentEnd:Point=null, nextSegmentStart:Point=null):void {
if (!prevSegmentEnd) {
prevSegmentEnd = segmentStart;
}
if (!nextSegmentStart) {
nextSegmentStart = segmentEnd;
}
var m1:Point = new Point((segmentEnd.x - prevSegmentEnd.x) / 2, (segmentEnd.y - prevSegmentEnd.y) / 2);
var m2:Point = new Point((nextSegmentStart.x - segmentStart.x) / 2, (nextSegmentStart.y - segmentStart.y) / 2);
var n:int = hermiteValues.length;
for (var i:int = 0; i < n; i += 4) {
var h00:Number = hermiteValues[i];
var h10:Number = hermiteValues[i + 1];
var h01:Number = hermiteValues[i + 2];
var h11:Number = hermiteValues[i + 3];
var px:Number = h00 * segmentStart.x + h10 * m1.x + h01 * segmentEnd.x + h11 * m2.x;
var py:Number = h00 * segmentStart.y + h10 * m1.y + h01 * segmentEnd.y + h11 * m2.y;
target.lineTo(px, py);
}
}
}
This is not a perfect solution. But unfortunately, I cannot piece together how to accomplish what I want using curveTo(). Note that GraphicsUtilities.drawPolyLine() does accomplish what I am attempting to do--the problem there is that it is inflexible and I cannot parse the code (more importantly, it doesn't appear to properly draw acute angles--correct me if I am wrong). If anyone can provide any insight, please post. For now, the above is my answer.
I code this, I think it may help:
SWF: http://dl.dropbox.com/u/2283327/stackoverflow/SplineTest.swf
Code: http://dl.dropbox.com/u/2283327/stackoverflow/SplineTest.as
I left a lot of comments on the code. I wish it helps!
Here is the theory behind the code:
A and C are the first and last point, B is the "control point" in AS3 you can draw the curve like this:
graphics.moveTo(A.x, A.y);
graphics.curveTo(B.x, B.y, C.x, C.y);
Now, D is the mid-point of the vector AC. And the mid-point of DB is the mid-point of the curve. Now what I did in the code was to move B exactly to D+DB*2 so, if you draw the curve using that point as control point, the mid-point of the curve will be B.
PS: Sorry for my poor Enlgish

Resources