I'm not very familiar working with svgs in js but here is something that is definitely strange.
I'm having an arrow and then a path that is supposed to fill that arrow to a certain extend. looks like this:
Now my aim is to be able to scale the white part but it should still stay inside that arrow.
Now the weird thing is that I cannot figure out how move the white part back into the right place. I've tried different attempts.
here is my current code (it works for scaleFactor 1 but not for any other):
var draw = SVG('arrow').size(500, 500);
var arrowPath=draw.polyline('10,243.495 202.918,15.482 397.199,245.107').fill('none').stroke({ width: 20 });
var arrow=draw.group();
arrow.add(arrowPath.clone());
var scaleFactor=0.5;
var fillArrow=draw.path('M357.669,198.387c-41.747,35.357-95.759,56.678-154.751,56.678c-58.991,0-113.003-21.32-154.75-56.676l154.75-182.907 L357.669,198.387z');
fillArrow.fill('#ffffee');
var moveX=(arrowPath.width()/2-fillArrow.width()/2)/scaleFactor+9.5;
console.log(moveX);
fillArrow.center(arrowPath.cx(), arrowPath.cy()).scale(scaleFactor);
//another attempt was
fillArrow.move(moveX,0);
When you are scaling, rotating and translating in SVG you are doing coordinate transforms. That is, you are actually not changing the object you are drawing but the coordinate system that you are drawing the object in. Think of it as pixel has a certain size on your screen, and if your do svgObject.scale(0.5) the pixel becomes half the size.
So if you draw a square by path('M10,10 L20,10 L20,20 L10,20 z') and then apply scale(0.5) it will look like you have drawn a path that looks like path('M5,5 L10,5 L10,10 L5,10 Z')
This might sound strange at first but, but alot of geometrical calculations becomes much simpler when you can do this.
You want to scale around the tip of the arrow (make sure that does not move). Then you should place that point in the origo (0,0) and draw the object around that point. Do that in a group. Because then you can translate the group coordinate system to the correct position.
var draw = SVG('arrow').size(600, 600);
// create a group
var arrow = draw.group();
// Draw the arrow path in the group
// I have placed the "tip" of the arrow in (0,0)
var arrowPath = arrow.polyline('-250,250 0,0 250,250').fill('none').stroke({
width: 20
});
// Draw the fill arrow in the group. Again, the point
// I which to scale around is placed at (0,0)
var fillArrow = arrow.path('M0,0L150,150,-150,150z').fill('#ffffee');
// Move the group to the position we like to display it in the SVG
arrow.move(260, 20);
var scaleFactor = 0.5
fillArrow.scale(scaleFactor);
And here is a working example where you can test and change the scale factor.
http://jsfiddle.net/ZmGQk/1/
And here is a good explanation on how the translate, rotate and scale works.
http://commons.oreilly.com/wiki/index.php/SVG_Essentials/Transforming_the_Coordinate_System
Related
I have a series of dots with connected lines that I am animating in an easel.js canvas. The dots move around, and the lines stay connected to them as they move. As the dots move, I'm animating their color, so I want the lines to animate color as well.
I tried calling a color tween on the line, but it requires that I cache the line first.
For a circle, that's easy - I get the radius and, since its registration is in the center, its x and y coordinates and width and height are easy to calculate (for a circle with r=100 at 50,50, its cache would be cache(0,0,100,100). But for a line, I'm not sure how to reference the right coordinates for the cache statement, especially since the line start position, end position, and length are always changing.
Anyone have a way to do this?
I'm using greensock's timelinemax / tweenlite with the easeljs plugin to handle all the animations, if that's helpful.
If TweenLite handles color tweens, then you should just be able to update the "style" of your line any time:
var shape = new createjs.Shape();
var colorCommand = shape.graphics.beginStroke("#000000").command;
shape.graphics.moveTo(0,0).lineTo(100,100); // Draw the line
// Any time
colorCommand.style = "#ff0000";
// So in a tween:
TweenLite.to(colorCommand, 20, {style:"#00ffff"});
If you are using EaselJS, you can also use TweenJS, which has a ColorPlugin. Using similar code:
createjs.Tween.get(colorCommand).to({style:"#00fffff"}, 20000);
Here is a fiddle I made tweening the color of a line with TweenJS https://jsfiddle.net/lannymcnie/5zxpb944/
Cheers.
I've already asked this same question months ago, but no one was able to answer me, even after making a fully functional example on Plunker, then, I am going to ask it again, and yes, I still have the same problem.
My problem: find the centre of an element who have some rotation in it, after resizing it, to use it as the new pivot of rotation.
In my practical example, it is possible to see the problem in action; I have created two circles to show the problem better. After rotating and resizing the element, it's possible to see how the red and blue circles are apart from each other.
Blue Circle: the "correct" position of the centre, achieved by setting the cx/cy coordinates as the calculated element centre, plus, applying the transform rotate in it. The transform translates the circle to the correct position.
Red Circle: same as the blue circle, minus the transform rotate, these values are the ones used as the rotation pivot for the transform rotate().
My assumptions until here: By applying the transform rotate() in the blue circle, I'm considering the rotation angle in the calculated centre, so all I have to do is replicate the matrix calculations made by the rotate() function. I'm already doing this with the four handles that the user can click to make a rotation, what could go wrong?
My goal: Resize an element with rotation keeping the pivot of rotation in the centre.
I think this answer gave me some info, the math here helped me with the rotation handles starting position, but still, I can't find the right way to calculate the new centre after the resize.
The example was made using D3js + AngularJS v1. I work actively with both, but I am new to the geometry math world.
Again, this is the project on Plunker.
To get the centre of the transformed and rotated element, the most accurate way would probably be to get the browser to calculate it for you.
First create an SVGPoint object to hold our original centre point.
var centre = svg.createSVGPoint();
Initialize this point with the centre of the original object. You can get that by calling getBBox() on the element, and performing a smiple calculation.
var bbox = obj.getBBox();
centre.x = bbox.x + bbox.width / 2;
centre.y = bbox.y + bbox.height / 2;
Next, get the transform matrix from the transform attribute of the transformed object
var matrix = transformedObj.transform.baseVal.consolidate().matrix
Now we can transform our SVGPoint object with this matrix.
var transformedCentre = centre.matrixTransform(matrix);
After this, the x and y properties of transformedCentre should be your transformed centre point.
This should work, but I haven't tested it.
I have a large circle with smaller ones inside made using two.js.
My problem is that these two do not rotate in their own place but in the top left axis.
I want the group of circles (circlesGroup) rotate only inside the large one in a static position. The circlesGroup and the large circle are grouped together as rotatoGroup.
two.bind('update', function(frameCount, timeDelta) {
circlesGroup.rotation = frameCount / 120;
});
two.bind('update', function(frameCount, timeDelta) {
rotatoGroup.rotation = frameCount / 60;
});
The whole code is in CodePen.
All visible shapes when invoked with two.make... ( circles, rectangles, polygons, and lines ) are oriented in the center like this Adobe Illustrator example:
When this shape's translation, rotation, or scale change those changes will be reflected as transformations about the center of the shape.
Two.Groups however do not behave this way. Think of them as display-less rectangles. They're origin, i.e group.translation vector, always begins at (0, 0). In your case you can deal with this by normalizing the translation your defining on all your circles.
Example 1: Predefined in normalized space
In this codepen example we're defining the position of all the circles around -100, 100, effectively half the radius in both positive-and-negative x-and-y directions. Once we've defined the circles within these constraints we can move the whole group with group.translation.set to place it in the center of the screen. Now when the circles rotate they are perceived as rotating around themselves.
Example 2: Normalizing after the fact
In this codepen example we're working with what we already have. A Two.Group that contains all of our shapes ( the bigger circle as well as the array of the smaller circles ). By using the method group.center(); ( line 31 ) we can normalize the children of the group to be around (0, 0). We can then change the translation of the group in order to be in the desired position.
N.B: This example is a bit complicated because it invokes underscore's defer method which forces the centering of the group after all the changes have been registered. I'm in the process of fixing this.
I've searched for the answer to this and have tried many proposed solutions, but none seem to work. I've been struggling with this forever so any insight is greatly appreciated.
I have 3 shapes (vectors I suppose) on a JS canvas, each with an orientation represented as degrees off of 0 and a width. I need to drag one of these shapes "straight out" from its orientation. This is difficult to explain in words so please view the graphic I created:
The middle (diagonal) shape is at 45 degrees. It's origin is the red dot, (x1,y1). The user drags the shape and their mouse lies at the green dot, (x2,y2). Since the shape's origin is in the lower left, I need to position the shape at the position of the lighter blue shape as if the user has dragged straight outward from the shape's origin.
I don't think it matters, but the library I'm using to do this is KineticJS. Here's the code and some information I have available which may help solve the problem. This code positions the shape on top of the mouse, which isn't what I want:
var rotationDeg = this.model.get("DisplayOri"), // rotation in degrees
rotationRadians = rotationDeg * Math.PI / 180, // rotation in rads
unchanged = this.content.getAbsolutePosition(), // {x,y} of the shape before any dragging
dragBoundFunc = function (changed) {
// called on a mouseMove event, so changed is always different and is the x,y of mouse on stage
var delta = {
x: changed.x - unchanged.x,
y: changed.y - unchanged.y
};
return changed; // go to the mouse position
};
[edit] I should mention that the obvious of "return delta" doesn't work.
It sounds like you want to constrain the movement of the object.
Determine the vector representing the constraint axis : that is, we only want motion to occur along this line. It appears from your drawing that this is in the direction of the short line from the red dot out to the left. That vector has a direction of -1/m where m is the slope of the line we are moving.
Constrain the movement. The movement is represented by the mouse move delta - but we only want the portion of that movement in the direction of the constraint axis. This is done with a dot product of the two vectors.
So in pseudo code
m = (line.y2 - line.y1)/(line.x2 - line.x1)
constraintSlope = -1/m
contraintVector = {1, constraintSlope} //unit vector in that direction
userMove = {x2-x1, y2-y1} //vector of mouse move direction
projection = userMove.x * constraintVector.x + userMove.y * constraintVector.y
translation = projection * constraintVector //scaled vector
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/