I am implementing perspective from scratch for an academic project. I am using "Computer Graphics: principles and practices", by Foley, van Dam, Feiner and Hughes (second edition in C).
I just followed the book by implementing all the matrices transformations needed to traslate, rotate, shear, scale, project, transform from perspective to parallel canonical view volumes and for clipping. The book apparently uses a right-handed coordinate system. However, I ended up with primitives appearing in a left-handed coordinate system and I cannot explain why.
Here are the matrices that I used:
Translation:
1, 0, 0, dx
0, 1, 0, dy
0, 0, 1, dz
0, 0, 0, 1
Rotation (to align a coordinate system (rx, ry, rz) to XYZ):
rx1, rx2, rx3, 0
ry1, ry2, ry3, 0
rz1, rz2, rz3, 0
0 , 0 , 0 , 1
Scale:
sx, 0 , 0 , 0
0 , sy, 0 , 0
0 , 0 , sz, 0
0 , 0 , 0 , 1
Shear XY:
1, 0, shx, 0
0, 1, shy, 0
0, 0, 1 , 0
0, 0, 0 , 1
Projecting onto a plane at z = d, with PRP at origin, looking in the positive z direction:
1, 0, 0 , 0
0, 1, 0 , 0
0, 0, 1 , 0
0, 0, 1/d, 0
Then given VRP, VPN, PRP, VUP, f and b (and the direction of projection dop), reduce the space to the canonical viewing volume for perspective using P:
rz = VPN / |VPN|
rx = (VUP x rz) / |VUP x rz|
ry = rz x rx
P = ScaleUniform(-1 / (vrp1Z + b)) *
Scale(-2 * vrp1Z / deltaU, -2 * vrp1Z / deltaV, 1) *
Shear(-dopX / dopZ, -dopY / dopZ) *
T(PRP) *
R(rx, ry, rz) *
T(-VRP)
Where vrp1 is ShearXY * T(-PRP) * (0, 0, 0, 1), deltaU and deltaV the width and height of the viewing window. dop is computed as CW - PRP, where CW is the center of the viewing window.
Then Projection(d) * P gives me the projection matrix.
I projected simple lines representing the unit vectors on x, y and z, but the representation that I obtained drawn on the screen was clearly a left handed coordinate system... Now I need to work in a right handed coordinate system, so is there a way to know where I did wrong?
Here is the code I used:
As you can see, the Z component of the scale matrix is of opposite sign, since clipping wasn't working properly because something was right-handed and something left-handed, but I couldn't discern what exactly, so I swapped the sign of the scale because it wasn't needed in a left-hand system.
Vector rz = vpn.toUnitVector();
Vector rx = vup.cross(rz).toUnitVector();
Vector ry = rz.cross(rx).toUnitVector();
Vector cw = viewWindow.getCenter();
Vector dop = cw - prp;
Matrix t1 = Matrix::traslation(-vrp[X], -vrp[Y], -vrp[Z]);
Matrix r = Matrix::rotation(rx, ry, rz);
Matrix t2 = Matrix::traslation(-prp[X], -prp[Y], -prp[Z]);
Matrix partial = t2 * r * t1;
Matrix shear = Matrix::shearXY(-dop[X] / dop[Z], -dop[Y] / dop[Z]);
Matrix inverseShear = Matrix::shearXY(dop[X] / dop[Z], dop[Y] / dop[Z]);
Vector vrp1 = shear * t2 * Vector(0, 0, 0, 1);
Matrix scale = Matrix::scale(
2 * vrp1[Z] / ((viewWindow.xMax - viewWindow.xMin) * (vrp1[Z] + b)),
2 * vrp1[Z] / ((viewWindow.yMax - viewWindow.yMin) * (vrp1[Z] + b)),
1 / (vrp1[Z] + b)); // HERE <--- WAS NEGATIVE
Matrix inverseScale = Matrix::scale(
((viewWindow.xMax - viewWindow.xMin) * (vrp1[Z] + b)) / (2 * vrp1[Z]),
((viewWindow.yMax - viewWindow.yMin) * (vrp1[Z] + b)) / (2 * vrp1[Z]),
(vrp1[Z] + b));
float zMin = -(vrp1[Z] + f) / (vrp1[Z] + b);
Matrix parallel = Perspective::toParallelCvv(zMin);
Matrix inverseParallel = Perspective::inverseToParallelCvv(zMin);
Matrix perspective = Perspective::copAtOrigin(-vrp1[Z]);
projection = perspective * shear * partial;
canonicalView = parallel * scale * shear * partial;
canonicalToProjection = perspective * inverseScale * inverseParallel;
see jsfiddle
Here's my code:
var paper = Raphael("holder");
function sector(cx, cy, r, startAngle, endAngle) {
var x1 = cx + r * Math.cos(-startAngle),
y1 = cy + r * Math.sin(-startAngle),
x2 = cx + r * Math.cos(-endAngle),
y2 = cy + r * Math.sin(-endAngle);
return ['M', cx, cy, 'L', x1, y1, 'A', r, r, 0, +(endAngle - startAngle > Math.PI), 0, x2, y2, 'z'];
}
var path = paper.path(sector(200, 200, 107, 0, 0.25)).attr({
'fill': '#fff',
'fill-opacity': 0.5,
'stroke': 'none'
});
path.animate({
path: sector(200, 200, 107, 0, Math.PI / 2)
}, 1000);
The problem is that in the intermediate animation it doesn't follow a circular path, I get this weird flattened thing instead:
How do I make the animation remain circular throughout?
I essentially want to create a "loading pie". The pie should animate into a full circle.
Animating from "empty" to 60% looks even worse: http://jsfiddle.net/mnbayazit/Fh43X/3/
Figured it out after digging through some of their examples.
var r = Raphael("holder");
r.customAttributes.segment = function (x, y, r, a1, a2) {
var flag = (a2 - a1) > 180,
clr = (a2 - a1) / 360;
a1 = (a1 % 360) * Math.PI / 180;
a2 = (a2 % 360) * Math.PI / 180;
return {
path: [
["M", x, y],
["l", r * Math.cos(a1), r * Math.sin(a1)],
["A", r, r, 0, +flag, 1, x + r * Math.cos(a2), y + r * Math.sin(a2)],
["z"]
]
};
};
var p = r.path().attr({
segment: [200, 200, 100, 0, 0],
stroke: 'none',
fill: '#fff',
'fill-opacity': 0.5
});
p.animate({
segment: [200, 200, 100, 0, 359]
}, 2000);
I am seeing an annoying wobble in my animation, I have stripped out the code which contains the actual animation:
var side = 400;
var paper = new Raphael($(this), 100, side);
paper.customAttributes.arc = function (xloc, yloc, value, total, R) {
var alpha = 360 / total * value,
a = (90 - alpha) * Math.PI / 180,
x = xloc + R * Math.cos(a),
y = yloc - R * Math.sin(a),
path;
if (total == value) {
path = [
["M", xloc, yloc - R],
["A", R, R, 0, 1, 1, xloc - 0.01, yloc - R]
];
} else {
path = [
["M", xloc, yloc - R],
["A", R, R, 0, +(alpha > 180), 1, x, y]
];
}
return {
path: path
};
};
var arcWidth = 180 - 120;
var strokeRadius = (120 + arcWidth/2);
var indicatorArc = paper.path().attr({
"stroke": "#4B6384",
"stroke-width": 100,
arc: [side/2, side/2, 0, 100, strokeRadius]
});
indicatorArc.animate({
arc: [side/2, side/2, 75, 100, strokeRadius]
}, 1500, "<>", function(){
// anim complete here
});
I have put it in a jsfiddle for you to see for yourself, please check in firefox and chrome, you will notice in chrome the edges wobble substantially, is there anything I can do to eliminate this?
fiddle here: run many times
So I know this is over two years old now, but if anyone comes across this issue, it's a known bug within Chrome's 2D drawing engine.
https://code.google.com/p/skia/issues/detail?id=2769
I need to draw concentric arcs of various sizes using raphael.js. I tried to understand the code behind http://raphaeljs.com/polar-clock.html, which is very similar to what I want, but, whithout comments, it is quite difficult to fathom.
Ideally, I would need a function that creates a path that is at a given distance from some center point, starts at some angle and ends at some other angle.
That answer is ok, but cant be animated. I ripped the important stuff out of polar-clock for you. Here is a red arc that animates growing. enjoy.
// Custom Arc Attribute, position x&y, value portion of total, total value, Radius
var archtype = Raphael("canvas", 200, 100);
archtype.customAttributes.arc = function (xloc, yloc, value, total, R) {
var alpha = 360 / total * value,
a = (90 - alpha) * Math.PI / 180,
x = xloc + R * Math.cos(a),
y = yloc - R * Math.sin(a),
path;
if (total == value) {
path = [
["M", xloc, yloc - R],
["A", R, R, 0, 1, 1, xloc - 0.01, yloc - R]
];
} else {
path = [
["M", xloc, yloc - R],
["A", R, R, 0, +(alpha > 180), 1, x, y]
];
}
return {
path: path
};
};
//make an arc at 50,50 with a radius of 30 that grows from 0 to 40 of 100 with a bounce
var my_arc = archtype.path().attr({
"stroke": "#f00",
"stroke-width": 14,
arc: [50, 50, 0, 100, 30]
});
my_arc.animate({
arc: [50, 50, 40, 100, 30]
}, 1500, "bounce");
Here's how I have done it. The following code allows you to specify a start and end angle as well as an inner and outer radius (useful for doing those trendy donut style pie charts). The solution doesn't rely on approximating a curve with line segments and can be animated as per the clock example mentioned in the original question.
First create your Raphael drawing area; the following assumes a div with id "raphael_paper" in your HTML file:
var paper = Raphael("raphael_paper", 800, 800);
to this Raphael object we add a custom arc attribute, a function which takes the center of a circle (x and y coords), a start angle, an end angle, an inner radius and an outer radius:
paper.customAttributes.arc = function (centerX, centerY, startAngle, endAngle, innerR, outerR) {
var radians = Math.PI / 180,
largeArc = +(endAngle - startAngle > 180);
// calculate the start and end points for both inner and outer edges of the arc segment
// the -90s are about starting the angle measurement from the top get rid of these if this doesn't suit your needs
outerX1 = centerX + outerR * Math.cos((startAngle-90) * radians),
outerY1 = centerY + outerR * Math.sin((startAngle-90) * radians),
outerX2 = centerX + outerR * Math.cos((endAngle-90) * radians),
outerY2 = centerY + outerR * Math.sin((endAngle-90) * radians),
innerX1 = centerX + innerR * Math.cos((endAngle-90) * radians),
innerY1 = centerY + innerR * Math.sin((endAngle-90) * radians),
innerX2 = centerX + innerR * Math.cos((startAngle-90) * radians),
innerY2 = centerY + innerR * Math.sin((startAngle-90) * radians);
// build the path array
var path = [
["M", outerX1, outerY1], //move to the start point
["A", outerR, outerR, 0, largeArc, 1, outerX2, outerY2], //draw the outer edge of the arc
["L", innerX1, innerY1], //draw a line inwards to the start of the inner edge of the arc
["A", innerR, innerR, 0, largeArc, 0, innerX2, innerY2], //draw the inner arc
["z"] //close the path
];
return {path: path};
};
now we can use this to draw arcs of a specified thickness, starting and ending wherever we want them to eg.
var redParams = {stroke: "#f00", "stroke-width": 1, fill:"#eee"},
greenParams = {stroke: "#0f0", "stroke-width": 1, fill:"#eee"},
blueParams = {stroke: "#00f", "stroke-width": 1, fill:"#eee"},
cx = 300, cy = 300, innerRadius = 100, outerRadius = 250,
var red = paper.path().attr(redParams).attr({arc: [cx, cy, 0, 90, innerRadius, outerRadius]});
var green = paper.path().attr(greenParams).attr({arc: [cx, cy, 270, 320, innerRadius, outerRadius]});
var blue = paper.path().attr(blueParams).attr({arc: [cx, cy, 95, 220, innerRadius, outerRadius]});
This should result in three grey arc segments with red, blue and green 1px borders.
Actually found the answer myself. I first thought of something fancy involving bezier curves, but this just works.
-> creates a path using SVG path syntax, which works as is with raphael
function arc(center, radius, startAngle, endAngle) {
angle = startAngle;
coords = toCoords(center, radius, angle);
path = "M " + coords[0] + " " + coords[1];
while(angle<=endAngle) {
coords = toCoords(center, radius, angle);
path += " L " + coords[0] + " " + coords[1];
angle += 1;
}
return path;
}
function toCoords(center, radius, angle) {
var radians = (angle/180) * Math.PI;
var x = center[0] + Math.cos(radians) * radius;
var y = center[1] + Math.sin(radians) * radius;
return [x, y];
}
Just to remove some guesswork from user592699's answer, this is the complete code that works:
<script src="raphael.js"></script>
<script>
var paper = Raphael(20, 20, 320, 320);
function arc(center, radius, startAngle, endAngle) {
angle = startAngle;
coords = toCoords(center, radius, angle);
path = "M " + coords[0] + " " + coords[1];
while(angle<=endAngle) {
coords = toCoords(center, radius, angle);
path += " L " + coords[0] + " " + coords[1];
angle += 1;
}
return path;
}
function toCoords(center, radius, angle) {
var radians = (angle/180) * Math.PI;
var x = center[0] + Math.cos(radians) * radius;
var y = center[1] + Math.sin(radians) * radius;
return [x, y];
}
paper.path(arc([100, 100], 80, 0, 270)); // draw an arc
// centered at (100, 100),
// radius 80, starting at degree 0,
// beginning at coordinate (80, 0)
// which is relative to the center
// of the circle,
// going clockwise, until 270 degree
</script>
For those who want the arc to be made with closed path and not stroke, I have extended genkilabs answer to make a solution. In cases when you need to give outer stroke to your arc, this might help.
// Custom Arc Attribute, position x&y, value portion of total, total value, Radius, width
var archtype = Raphael("canvas", 200, 100);
archtype.customAttributes.arc = function (xloc, yloc, value, total, R, width) {
if(!width) width = R * 0.4;
var alpha = 360 / total * value,
a = (90 - alpha) * Math.PI / 180,
w = width / 2,
r1 = R + w,
r2 = R - w,
x1 = xloc + r1 * Math.cos(a),
y1 = yloc - r1 * Math.sin(a),
x2 = xloc + r2 * Math.cos(a),
y2 = yloc - r2 * Math.sin(a),
path;
if (total == value) {
path = [
["M", xloc, yloc - r1],
["A", r1, r1, 0, 1, 1, xloc - 0.01, yloc - r1],
["Z"],
["M", xloc - 0.01, yloc - r2],
["A", r2, r2, 0, 1, 0, xloc, yloc - r2],
["Z"]
];
} else {
path = [
["M", xloc, yloc - r1],
["A", r1, r1, 0, +(alpha > 180), 1, x1, y1],
["L", x2, y2],
["A", r2, r2, 0, +(alpha > 180), 0, xloc, yloc - r2],
["L", xloc, yloc - r1],
["Z"]
];
}
return {
path: path
};
};
//make an arc at 50,50 with a radius of 30 that grows from 0 to 40 of 100 with a bounce
var my_arc = archtype.path().attr({
"fill": "#00f",
"stroke": "#f00",
"stroke-width": 5,
arc: [50, 50, 0, 100, 30]
});
my_arc.animate({
arc: [50, 50, 40, 100, 30]
}, 1500, "bounce");
JSFiddle
You can also do this without having to use loops. The following achieves this and works with negative angles as well.
Pass in a Raphael object as r. The angles start with 0 degrees, which is the top of the circle rather than the right as was listed in a couple of other solutions.
function drawArc(r, centerX, centerY, radius, startAngle, endAngle) {
var startX = centerX+radius*Math.cos((90-startAngle)*Math.PI/180);
var startY = centerY-radius*Math.sin((90-startAngle)*Math.PI/180);
var endX = centerX+radius*Math.cos((90-endAngle)*Math.PI/180);
var endY = centerY-radius*Math.sin((90-endAngle)*Math.PI/180);
var flg1 = 0;
if (startAngle>endAngle)
flg1 = 1;
else if (startAngle<180 && endAngle<180)
flg1 = 0;
else if (startAngle>180 && endAngle>180)
flg1 = 0;
else if (startAngle<180 && endAngle>180)
flg1 = 0; // edited for bugfix here, previously this was 1
else if (startAngle>180 && endAngle<180)
flg1 = 1;
return r.path([['M',startX, startY],['A',radius,radius,0,flg1,1,endX,endY]]);
};
I have adapted genkilabs answer to include rotation and inversion abilities. Also, how much of the ring is filled was changed to a single-number percent. (The inversion was adapted from this post). Hope it's helpful!
paper.customAttributes.arc = function (xloc, yloc, percent, rad, rot, invert) {
var alpha = 3.6 * percent,
a = (90 - alpha) * Math.PI / 180,
x = xloc + rad * Math.cos(a),
y = yloc - rad * Math.sin(a),
path;
if (invert) {
x = xloc - rad * Math.cos(a);
}
if (percent >= 100) {
path = [
["M", xloc, yloc - rad],
["A", rad, rad, 0, 1, 1, xloc - 0.01, yloc - rad]
];
} else {
path = [
["M", xloc, yloc - rad],
["A", rad, rad, 0, +(alpha > 180), +(!invert), x, y]
];
}
return {
path: path,
transform: "r"+rot+","+xloc+","+yloc,
};
};