TextPath extends Shape instead of Path. Extracted common path functions into PathHelper.js. Updated unit tests.

This commit is contained in:
Jason Follas 2012-07-27 12:25:36 -04:00
parent eccd8b7e64
commit 5d77471f7e
4 changed files with 3969 additions and 3912 deletions

View File

@ -9,20 +9,19 @@
* @param {Object} config * @param {Object} config
*/ */
Kinetic.Path = Kinetic.Shape.extend({ Kinetic.Path = Kinetic.Shape.extend({
init: function(config) { init : function (config) {
this.shapeType = "Path"; this.shapeType = "Path";
this.dataArray = []; this.dataArray = [];
var that = this; var that = this;
if (config.drawFunc == null) { config.drawFunc = function (context) {
config.drawFunc = function(context) {
var ca = this.dataArray; var ca = this.dataArray;
// context position // context position
context.beginPath(); context.beginPath();
for(var n = 0; n < ca.length; n++) { for (var n = 0; n < ca.length; n++) {
var c = ca[n].command; var c = ca[n].command;
var p = ca[n].points; var p = ca[n].points;
switch(c) { switch (c) {
case 'L': case 'L':
context.lineTo(p[0], p[1]); context.lineTo(p[0], p[1]);
break; break;
@ -36,7 +35,14 @@ Kinetic.Path = Kinetic.Shape.extend({
context.quadraticCurveTo(p[0], p[1], p[2], p[3]); context.quadraticCurveTo(p[0], p[1], p[2], p[3]);
break; break;
case 'A': case 'A':
var cx = p[0], cy = p[1], rx = p[2], ry = p[3], theta = p[4], dTheta = p[5], psi = p[6], fs = p[7]; var cx = p[0],
cy = p[1],
rx = p[2],
ry = p[3],
theta = p[4],
dTheta = p[5],
psi = p[6],
fs = p[7];
var r = (rx > ry) ? rx : ry; var r = (rx > ry) ? rx : ry;
var scaleX = (rx > ry) ? 1 : rx / ry; var scaleX = (rx > ry) ? 1 : rx / ry;
@ -59,14 +65,13 @@ Kinetic.Path = Kinetic.Shape.extend({
this.fill(context); this.fill(context);
this.stroke(context); this.stroke(context);
}; };
}
// call super constructor // call super constructor
this._super(config); this._super(config);
this.dataArray = this._getDataArray(); this.dataArray = this._getDataArray();
this.on('dataChange', function() { this.on('dataChange', function () {
that.dataArray = that._getDataArray(); that.dataArray = that._getDataArray();
}); });
}, },
@ -76,7 +81,7 @@ Kinetic.Path = Kinetic.Shape.extend({
* L data for the purpose of high performance Path * L data for the purpose of high performance Path
* rendering * rendering
*/ */
_getDataArray: function() { _getDataArray : function () {
// Path Data Segment must begin with a moveTo // Path Data Segment must begin with a moveTo
//m (x y)+ Relative moveTo (subsequent points are treated as lineTo) //m (x y)+ Relative moveTo (subsequent points are treated as lineTo)
@ -104,7 +109,7 @@ Kinetic.Path = Kinetic.Shape.extend({
var cs = this.attrs.data; var cs = this.attrs.data;
// return early if data is not defined // return early if data is not defined
if(!this.attrs.data) { if (!this.attrs.data) {
return []; return [];
} }
// command chars // command chars
@ -112,7 +117,7 @@ Kinetic.Path = Kinetic.Shape.extend({
// convert white spaces to commas // convert white spaces to commas
cs = cs.replace(new RegExp(' ', 'g'), ','); cs = cs.replace(new RegExp(' ', 'g'), ',');
// create pipes so that we can split the data // create pipes so that we can split the data
for(var n = 0; n < cc.length; n++) { for (var n = 0; n < cc.length; n++) {
cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]); cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]);
} }
// create array // create array
@ -121,7 +126,7 @@ Kinetic.Path = Kinetic.Shape.extend({
// init context point // init context point
var cpx = 0; var cpx = 0;
var cpy = 0; var cpy = 0;
for(var n = 1; n < arr.length; n++) { for (var n = 1; n < arr.length; n++) {
var str = arr[n]; var str = arr[n];
var c = str.charAt(0); var c = str.charAt(0);
str = str.slice(1); str = str.slice(1);
@ -131,24 +136,24 @@ Kinetic.Path = Kinetic.Shape.extend({
str = str.replace(new RegExp('-', 'g'), ',-'); str = str.replace(new RegExp('-', 'g'), ',-');
str = str.replace(new RegExp('e,-', 'g'), 'e-'); str = str.replace(new RegExp('e,-', 'g'), 'e-');
var p = str.split(','); var p = str.split(',');
if(p.length > 0 && p[0] === '') { if (p.length > 0 && p[0] === '') {
p.shift(); p.shift();
} }
// convert strings to floats // convert strings to floats
for(var i = 0; i < p.length; i++) { for (var i = 0; i < p.length; i++) {
p[i] = parseFloat(p[i]); p[i] = parseFloat(p[i]);
} }
while (p.length > 0) {
while(p.length > 0) { if (isNaN(p[0])) // case for a trailing comma before next command
if(isNaN(p[0]))// case for a trailing comma before next command
break; break;
var cmd = undefined; var cmd = null;
var points = []; var points = [];
var startX = cpx, startY = cpy; var startX = cpx,
startY = cpy;
// convert l, H, h, V, and v to L // convert l, H, h, V, and v to L
switch(c) { switch (c) {
// Note: Keep the lineTo's above the moveTo's in this switch // Note: Keep the lineTo's above the moveTo's in this switch
case 'l': case 'l':
@ -211,30 +216,32 @@ Kinetic.Path = Kinetic.Shape.extend({
points.push(cpx + p.shift(), cpy + p.shift(), cpx + p.shift(), cpy + p.shift()); points.push(cpx + p.shift(), cpy + p.shift(), cpx + p.shift(), cpy + p.shift());
cpx += p.shift(); cpx += p.shift();
cpy += p.shift(); cpy += p.shift();
cmd = 'C' cmd = 'C';
points.push(cpx, cpy); points.push(cpx, cpy);
break; break;
case 'S': case 'S':
var ctlPtx = cpx, ctlPty = cpy; var ctlPtx = cpx,
ctlPty = cpy;
var prevCmd = ca[ca.length - 1]; var prevCmd = ca[ca.length - 1];
if(prevCmd.command === 'C') { if (prevCmd.command === 'C') {
ctlPtx = cpx + (cpx - prevCmd.points[2]); ctlPtx = cpx + (cpx - prevCmd.points[2]);
ctlPty = cpy + (cpy - prevCmd.points[3]); ctlPty = cpy + (cpy - prevCmd.points[3]);
} }
points.push(ctlPtx, ctlPty, p.shift(), p.shift()) points.push(ctlPtx, ctlPty, p.shift(), p.shift());
cpx = p.shift(); cpx = p.shift();
cpy = p.shift(); cpy = p.shift();
cmd = 'C'; cmd = 'C';
points.push(cpx, cpy); points.push(cpx, cpy);
break; break;
case 's': case 's':
var ctlPtx = cpx, ctlPty = cpy; var ctlPtx = cpx,
ctlPty = cpy;
var prevCmd = ca[ca.length - 1]; var prevCmd = ca[ca.length - 1];
if(prevCmd.command === 'C') { if (prevCmd.command === 'C') {
ctlPtx = cpx + (cpx - prevCmd.points[2]); ctlPtx = cpx + (cpx - prevCmd.points[2]);
ctlPty = cpy + (cpy - prevCmd.points[3]); ctlPty = cpy + (cpy - prevCmd.points[3]);
} }
points.push(ctlPtx, ctlPty, cpx + p.shift(), cpy + p.shift()) points.push(ctlPtx, ctlPty, cpx + p.shift(), cpy + p.shift());
cpx += p.shift(); cpx += p.shift();
cpy += p.shift(); cpy += p.shift();
cmd = 'C'; cmd = 'C';
@ -250,13 +257,14 @@ Kinetic.Path = Kinetic.Shape.extend({
points.push(cpx + p.shift(), cpy + p.shift()); points.push(cpx + p.shift(), cpy + p.shift());
cpx += p.shift(); cpx += p.shift();
cpy += p.shift(); cpy += p.shift();
cmd = 'Q' cmd = 'Q';
points.push(cpx, cpy); points.push(cpx, cpy);
break; break;
case 'T': case 'T':
var ctlPtx = cpx, ctlPty = cpy; var ctlPtx = cpx,
ctlPty = cpy;
var prevCmd = ca[ca.length - 1]; var prevCmd = ca[ca.length - 1];
if(prevCmd.command === 'Q') { if (prevCmd.command === 'Q') {
ctlPtx = cpx + (cpx - prevCmd.points[0]); ctlPtx = cpx + (cpx - prevCmd.points[0]);
ctlPty = cpy + (cpy - prevCmd.points[1]); ctlPty = cpy + (cpy - prevCmd.points[1]);
} }
@ -266,9 +274,10 @@ Kinetic.Path = Kinetic.Shape.extend({
points.push(ctlPtx, ctlPty, cpx, cpy); points.push(ctlPtx, ctlPty, cpx, cpy);
break; break;
case 't': case 't':
var ctlPtx = cpx, ctlPty = cpy; var ctlPtx = cpx,
ctlPty = cpy;
var prevCmd = ca[ca.length - 1]; var prevCmd = ca[ca.length - 1];
if(prevCmd.command === 'Q') { if (prevCmd.command === 'Q') {
ctlPtx = cpx + (cpx - prevCmd.points[0]); ctlPtx = cpx + (cpx - prevCmd.points[0]);
ctlPty = cpy + (cpy - prevCmd.points[1]); ctlPty = cpy + (cpy - prevCmd.points[1]);
} }
@ -278,240 +287,57 @@ Kinetic.Path = Kinetic.Shape.extend({
points.push(ctlPtx, ctlPty, cpx, cpy); points.push(ctlPtx, ctlPty, cpx, cpy);
break; break;
case 'A': case 'A':
var rx = p.shift(), ry = p.shift(), psi = p.shift(), fa = p.shift(), fs = p.shift(); var rx = p.shift(),
var x1 = cpx, y1 = cpy; ry = p.shift(),
cpx = p.shift(), cpy = p.shift(); psi = p.shift(),
fa = p.shift(),
fs = p.shift();
var x1 = cpx,
y1 = cpy;
cpx = p.shift(),
cpy = p.shift();
cmd = 'A'; cmd = 'A';
points = this._convertEndpointToCenterParameterization(x1, y1, cpx, cpy, fa, fs, rx, ry, psi); points = Kinetic.PathHelper.convertEndpointToCenterParameterization(x1, y1, cpx, cpy, fa, fs, rx, ry, psi);
break; break;
case 'a': case 'a':
var rx = p.shift(), ry = p.shift(), psi = p.shift(), fa = p.shift(), fs = p.shift(); var rx = p.shift(),
var x1 = cpx, y1 = cpy; ry = p.shift(),
cpx += p.shift(), cpy += p.shift(); psi = p.shift(),
fa = p.shift(),
fs = p.shift();
var x1 = cpx,
y1 = cpy;
cpx += p.shift(),
cpy += p.shift();
cmd = 'A'; cmd = 'A';
points = this._convertEndpointToCenterParameterization(x1, y1, cpx, cpy, fa, fs, rx, ry, psi); points = Kinetic.PathHelper.convertEndpointToCenterParameterization(x1, y1, cpx, cpy, fa, fs, rx, ry, psi);
break; break;
} }
ca.push({ ca.push({
command: cmd || c, command : cmd || c,
points: points, points : points,
start: {x: startX, y: startY}, start : {
pathLength: this._calcLength(startX, startY, cmd || c, points) x : startX,
y : startY
},
pathLength : Kinetic.PathHelper.calcLength(startX, startY, cmd || c, points)
}); });
} }
if(c === 'z' || c === 'Z') if (c === 'z' || c === 'Z')
ca.push({ ca.push({
command: 'z', command : 'z',
points: [], points : [],
start: undefined, start : undefined,
pathLength: 0 pathLength : 0
}); });
} }
return ca; return ca;
},
_convertEndpointToCenterParameterization: function(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg) {
// Derived from: http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes
var psi = psiDeg * (Math.PI / 180.0);
var xp = Math.cos(psi) * (x1 - x2) / 2.0 + Math.sin(psi) * (y1 - y2) / 2.0;
var yp = -1 * Math.sin(psi) * (x1 - x2) / 2.0 + Math.cos(psi) * (y1 - y2) / 2.0;
var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
if(lambda > 1) {
rx *= Math.sqrt(lambda);
ry *= Math.sqrt(lambda);
} }
});
var f = Math.sqrt((((rx * rx) * (ry * ry)) - ((rx * rx) * (yp * yp)) - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp) + (ry * ry) * (xp * xp)));
if(fa == fs)
f *= -1;
if(isNaN(f))
f = 0;
var cxp = f * rx * yp / ry;
var cyp = f * -ry * xp / rx;
var cx = (x1 + x2) / 2.0 + Math.cos(psi) * cxp - Math.sin(psi) * cyp;
var cy = (y1 + y2) / 2.0 + Math.sin(psi) * cxp + Math.cos(psi) * cyp;
var vMag = function(v) {
return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
}
var vRatio = function(u, v) {
return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v))
}
var vAngle = function(u, v) {
return (u[0] * v[1] < u[1] * v[0] ? -1 : 1) * Math.acos(vRatio(u, v));
}
var theta = vAngle([1, 0], [(xp - cxp) / rx, (yp - cyp) / ry]);
var u = [(xp - cxp) / rx, (yp - cyp) / ry];
var v = [(-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry];
var dTheta = vAngle(u, v);
if(vRatio(u, v) <= -1)
dTheta = Math.PI;
if(vRatio(u, v) >= 1)
dTheta = 0;
if(fs == 0 && dTheta > 0)
dTheta = dTheta - 2 * Math.PI;
if(fs == 1 && dTheta < 0)
dTheta = dTheta + 2 * Math.PI;
return [cx, cy, rx, ry, theta, dTheta, psi, fs];
},
_calcLength: function(x, y, cmd, points) {
switch (cmd) {
case 'L':
return this._getLineLength(x, y, points[0], points[1]);
case 'C':
// Approximates by breaking curve into 100 line segments
var len = 0.0;
var p1 = this._getPointOnCubicBezier(0, x, y, points[0], points[1], points[2], points[3], points[4], points[5]);
for (t=0.01; t <= 1; t += 0.01)
{
var p2 = this._getPointOnCubicBezier(t, x, y, points[0], points[1], points[2], points[3], points[4], points[5]);
len += this._getLineLength(p1.x, p1.y, p2.x, p2.y);
p1 = p2;
}
return len;
case 'Q':
// Approximates by breaking curve into 100 line segments
var len = 0.0;
var p1 = this._getPointOnQuadraticBezier(0, x, y, points[0], points[1], points[2], points[3]);
for (t=0.01; t <= 1; t += 0.01)
{
var p2 = this._getPointOnQuadraticBezier(t, x, y, points[0], points[1], points[2], points[3]);
len += this._getLineLength(p1.x, p1.y, p2.x, p2.y);
p1 = p2;
}
return len;
case 'A':
// Approximates by breaking curve into line segments
var len = 0.0;
var start = points[4]; // 4 = theta
var dTheta = points[5];// 5 = dTheta
var end = points[4] + dTheta;
var inc = Math.PI / 180.0; // 1 degree resolution
if (Math.abs(start - end) < inc)
inc = Math.abs(start - end);
// Note: for purpose of calculating arc length, not going to worry about rotating X-axis by angle psi
var p1 = this._getPointOnEllipticalArc(points[0], points[1], points[2], points[3], start, 0);
if (dTheta < 0) // clockwise
{
for (t=start - inc; t > end; t -= inc)
{
var p2 = this._getPointOnEllipticalArc(points[0], points[1], points[2], points[3], t, 0)
len += this._getLineLength(p1.x, p1.y, p2.x, p2.y);
p1 = p2
}
}
else // counter-clockwise
{
for (t=start + inc; t < end; t += inc)
{
var p2 = this._getPointOnEllipticalArc(points[0], points[1], points[2], points[3], t, 0)
len += this._getLineLength(p1.x, p1.y, p2.x, p2.y);
p1 = p2
}
}
var p2 = this._getPointOnEllipticalArc(points[0], points[1], points[2], points[3], end, 0)
len += this._getLineLength(p1.x, p1.y, p2.x, p2.y);
return len;
}
return 0;
},
_getLineLength: function(x1, y1, x2, y2) {
return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
},
_getPointOnLine: function(dist, P1x, P1y, P2x, P2y, fromX, fromY) {
if (fromX === undefined)
fromX = P1x;
if (fromY === undefined)
fromY = P1y;
var m = (P2y - P1y) / ((P2x - P1x) + .00000001);
var b = -1 * m * P1x + P1y;
var run = Math.sqrt(dist * dist / (1 + m * m));
var rise = m * run;
if ((fromY - P1y) / ((fromX - P1x) + .00000001) === m)
{
return {x: fromX + run, y: fromY + rise};
}
else
{
var ix, iy;
var len = this._getLineLength(P1x, P1y, P2x, P2y)
if (len < 0.00000001)
return undefined;
var u = (((fromX - P1x) * (P2x - P1x)) + ((fromY - P1y) * (P2y - P1y)))
u = u / (len * len)
ix = P1x + u * (P2x - P1x)
iy = P1y + u * (P2y - P1y)
var pRise = this._getLineLength(fromX, fromY, ix, iy);
var pRun = Math.sqrt(dist * dist - pRise * pRise);
run = Math.sqrt(pRun * pRun / (1 + m * m));
rise = m * run;
return {x: ix + run, y: iy + rise};
}
},
_getPointOnCubicBezier: function(pct, P1x, P1y, P2x, P2y, P3x, P3y, P4x, P4y) {
function CB1(t) { return t * t * t }
function CB2(t) { return 3 * t * t * (1 - t) }
function CB3(t) { return 3 * t * (1 - t) * (1 - t) }
function CB4(t) { return (1 - t) * (1 - t) * (1 - t) }
var x = P4x * CB1(pct) + P3x * CB2(pct) + P2x * CB3(pct) + P1x * CB4(pct);
var y = P4y * CB1(pct) + P3y * CB2(pct) + P2y * CB3(pct) + P1y * CB4(pct);
return {x: x, y: y};
},
_getPointOnQuadraticBezier: function(pct, P1x, P1y, P2x, P2y, P3x, P3y) {
function QB1(t) { return t * t }
function QB2(t) { return 2 * t * (1 - t) }
function QB3(t) { return (1 - t) * (1 - t) }
var x = P3x * QB1(pct) + P2x * QB2(pct) + P1x * QB3(pct);
var y = P3y * QB1(pct) + P2y * QB2(pct) + P1y * QB3(pct);
return {x: x, y: y};
},
_getPointOnEllipticalArc: function(cx, cy, rx, ry, theta, psi) {
var cosPsi = Math.cos(psi), sinPsi = Math.sin(psi);
var pt = {x: rx * Math.cos(theta), y: ry * Math.sin(theta)};
return {x: cx + (pt.x * cosPsi - pt.y * sinPsi), y: cy + (pt.x * sinPsi + pt.y * cosPsi)};
}
});
// add getters setters // add getters setters
Kinetic.Node.addGettersSetters(Kinetic.Path, ['data']); Kinetic.Node.addGettersSetters(Kinetic.Path, ['data']);
@ -530,4 +356,4 @@ Kinetic.Node.addGettersSetters(Kinetic.Path, ['data']);
* get SVG path data string * get SVG path data string
* @name getData * @name getData
* @methodOf Kinetic.Path.prototype * @methodOf Kinetic.Path.prototype
*/ */

View File

@ -8,21 +8,25 @@
* @augments Kinetic.Path * @augments Kinetic.Path
* @param {Object} config * @param {Object} config
*/ */
Kinetic.TextPath = Kinetic.Path.extend({ Kinetic.TextPath = Kinetic.Shape.extend({
init: function(config) { init : function (config) {
this.setDefaultAttrs({ this.setDefaultAttrs({
fontFamily: 'Calibri', fontFamily : 'Calibri',
fontSize: 12, fontSize : 12,
fontStyle: 'normal', fontStyle : 'normal',
detectionType: 'path', detectionType : 'path',
text: '' text : ''
}); });
this.dummyCanvas = document.createElement('canvas'); this.dummyCanvas = document.createElement('canvas');
this.shapeType = "TextPath"; this.shapeType = "TextPath";
this.dataArray = [];
var that = this; var that = this;
config.drawFunc = function(context) { this._getDataArray = Kinetic.Path.prototype._getDataArray;
config.drawFunc = function (context) {
var charArr = this.charArr; var charArr = this.charArr;
context.font = this.attrs.fontStyle + ' ' + this.attrs.fontSize + 'pt ' + this.attrs.fontFamily; context.font = this.attrs.fontStyle + ' ' + this.attrs.fontSize + 'pt ' + this.attrs.fontFamily;
@ -32,8 +36,7 @@ Kinetic.TextPath = Kinetic.Path.extend({
var glyphInfo = this.glyphInfo; var glyphInfo = this.glyphInfo;
for (var i=0; i < glyphInfo.length; i++) for (var i = 0; i < glyphInfo.length; i++) {
{
context.save(); context.save();
var p0 = glyphInfo[i].p0; var p0 = glyphInfo[i].p0;
@ -67,9 +70,15 @@ Kinetic.TextPath = Kinetic.Path.extend({
// call super constructor // call super constructor
this._super(config); this._super(config);
this.dataArray = this._getDataArray();
this.on('dataChange', function () {
that.dataArray = that._getDataArray();
});
// update text data for certain attr changes // update text data for certain attr changes
var attrs = ['padding', 'text', 'textStroke', 'textStrokeWidth']; var attrs = ['padding', 'text', 'textStroke', 'textStrokeWidth'];
for(var n = 0; n < attrs.length; n++) { for (var n = 0; n < attrs.length; n++) {
var attr = attrs[n]; var attr = attrs[n];
this.on(attr + 'Change', that._setTextData); this.on(attr + 'Change', that._setTextData);
} }
@ -79,16 +88,16 @@ Kinetic.TextPath = Kinetic.Path.extend({
/** /**
* get text width in pixels * get text width in pixels
*/ */
getTextWidth: function() { getTextWidth : function () {
return this.textWidth; return this.textWidth;
}, },
/** /**
* get text height in pixels * get text height in pixels
*/ */
getTextHeight: function() { getTextHeight : function () {
return this.textHeight; return this.textHeight;
}, },
_getTextSize: function(text) { _getTextSize : function (text) {
var dummyCanvas = this.dummyCanvas; var dummyCanvas = this.dummyCanvas;
var context = dummyCanvas.getContext('2d'); var context = dummyCanvas.getContext('2d');
@ -100,14 +109,14 @@ Kinetic.TextPath = Kinetic.Path.extend({
context.restore(); context.restore();
return { return {
width: metrics.width, width : metrics.width,
height: parseInt(this.attrs.fontSize, 10) height : parseInt(this.attrs.fontSize, 10)
}; };
}, },
/** /**
* set text data. * set text data.
*/ */
_setTextData: function() { _setTextData : function () {
var that = this; var that = this;
var size = this._getTextSize(this.attrs.text); var size = this._getTextSize(this.attrs.text);
@ -118,13 +127,14 @@ Kinetic.TextPath = Kinetic.Path.extend({
var charArr = this.attrs.text.split(''); var charArr = this.attrs.text.split('');
var p0 = undefined; var p0,
var p1 = undefined; p1,
var pathCmd = undefined; pathCmd;
var pIndex = -1; var pIndex = -1;
var currentT = 0; var currentT = 0;
var getNextPathSegment = function() { var getNextPathSegment = function () {
currentT = 0; currentT = 0;
var pathData = that.dataArray; var pathData = that.dataArray;
@ -133,16 +143,18 @@ Kinetic.TextPath = Kinetic.Path.extend({
pIndex = i; pIndex = i;
return pathData[i]; return pathData[i];
} } else if (pathData[i].command == 'M') {
else if (pathData[i].command == 'M') { p0 = {
p0 = {x: pathData[i].points[0], y: pathData[i].points[1]}; x : pathData[i].points[0],
y : pathData[i].points[1]
};
} }
} }
return {}; return {};
} };
var findSegmentToFitCharacter = function(c, before) { var findSegmentToFitCharacter = function (c, before) {
var glyphWidth = that._getTextSize(c).width; var glyphWidth = that._getTextSize(c).width;
@ -151,42 +163,39 @@ Kinetic.TextPath = Kinetic.Path.extend({
var needNextSegment = false; var needNextSegment = false;
p1 = undefined; p1 = undefined;
while (Math.abs(glyphWidth - currLen) / glyphWidth > 0.01 && attempts < 25) { while (Math.abs(glyphWidth - currLen) / glyphWidth > 0.01 && attempts < 25) {
attempts++; attempts++;
var cumulativePathLength = currLen; var cumulativePathLength = currLen;
while (pathCmd === undefined) { while (pathCmd === undefined) {
pathCmd = getNextPathSegment(); pathCmd = getNextPathSegment();
if (pathCmd && cumulativePathLength + pathCmd.pathLength < glyphWidth) if (pathCmd && cumulativePathLength + pathCmd.pathLength < glyphWidth) {
{
cumulativePathLength += pathCmd.pathLength; cumulativePathLength += pathCmd.pathLength;
pathCmd = undefined; pathCmd = undefined;
} }
} }
if (pathCmd === {} || p0 === undefined) if (pathCmd === {}
|| p0 === undefined)
return undefined; return undefined;
var needNewSegment = false; var needNewSegment = false;
switch(pathCmd.command) { switch (pathCmd.command) {
case 'L': case 'L':
if (that._getLineLength(p0.x, p0.y, pathCmd.points[0], pathCmd.points[1]) > glyphWidth) if (Kinetic.PathHelper.getLineLength(p0.x, p0.y, pathCmd.points[0], pathCmd.points[1]) > glyphWidth) {
{ p1 = Kinetic.PathHelper.getPointOnLine(glyphWidth, p0.x, p0.y, pathCmd.points[0], pathCmd.points[1], p0.x, p0.y);
p1 = that._getPointOnLine(glyphWidth, p0.x, p0.y, pathCmd.points[0], pathCmd.points[1], p0.x, p0.y); } else
}
else
pathCmd = undefined; pathCmd = undefined;
break; break;
case 'A': case 'A':
var start = pathCmd.points[4]; // 4 = theta var start = pathCmd.points[4]; // 4 = theta
var dTheta = pathCmd.points[5];// 5 = dTheta var dTheta = pathCmd.points[5]; // 5 = dTheta
var end = pathCmd.points[4] + dTheta; var end = pathCmd.points[4] + dTheta;
if (currentT == 0) if (currentT === 0)
currentT = start + 0.00000001; // Just in case start is 0 currentT = start + 0.00000001; // Just in case start is 0
else if (glyphWidth > currLen) else if (glyphWidth > currLen)
currentT += (Math.PI / 180.0) * dTheta / Math.abs(dTheta); currentT += (Math.PI / 180.0) * dTheta / Math.abs(dTheta);
@ -199,16 +208,15 @@ Kinetic.TextPath = Kinetic.Path.extend({
needNewSegment = true; needNewSegment = true;
} }
p1 = that._getPointOnEllipticalArc(pathCmd.points[0], pathCmd.points[1], pathCmd.points[2], pathCmd.points[3], currentT, pathCmd.points[6]); p1 = Kinetic.PathHelper.getPointOnEllipticalArc(pathCmd.points[0], pathCmd.points[1], pathCmd.points[2], pathCmd.points[3], currentT, pathCmd.points[6]);
break; break;
case 'C': case 'C':
if (currentT == 0) { if (currentT === 0) {
if (glyphWidth > pathCmd.pathLength) if (glyphWidth > pathCmd.pathLength)
currentT = 0.00000001; currentT = 0.00000001;
else else
currentT = glyphWidth / pathCmd.pathLength; currentT = glyphWidth / pathCmd.pathLength;
} } else if (glyphWidth > currLen)
else if (glyphWidth > currLen)
currentT += (glyphWidth - currLen) / pathCmd.pathLength; currentT += (glyphWidth - currLen) / pathCmd.pathLength;
else else
currentT -= (currLen - glyphWidth) / pathCmd.pathLength; currentT -= (currLen - glyphWidth) / pathCmd.pathLength;
@ -218,10 +226,10 @@ Kinetic.TextPath = Kinetic.Path.extend({
needNewSegment = true; needNewSegment = true;
} }
p1 = that._getPointOnCubicBezier(currentT, pathCmd.start.x, pathCmd.start.y, pathCmd.points[0], pathCmd.points[1], pathCmd.points[2], pathCmd.points[3], pathCmd.points[4], pathCmd.points[5]) p1 = Kinetic.PathHelper.getPointOnCubicBezier(currentT, pathCmd.start.x, pathCmd.start.y, pathCmd.points[0], pathCmd.points[1], pathCmd.points[2], pathCmd.points[3], pathCmd.points[4], pathCmd.points[5]);
break; break;
case 'Q': case 'Q':
if (currentT == 0) if (currentT === 0)
currentT = glyphWidth / pathCmd.pathLength; currentT = glyphWidth / pathCmd.pathLength;
else if (glyphWidth > currLen) else if (glyphWidth > currLen)
currentT += (glyphWidth - currLen) / pathCmd.pathLength; currentT += (glyphWidth - currLen) / pathCmd.pathLength;
@ -233,14 +241,13 @@ Kinetic.TextPath = Kinetic.Path.extend({
needNewSegment = true; needNewSegment = true;
} }
p1 = that._getPointOnQuadraticBezier(currentT, pathCmd.start.x, pathCmd.start.y, pathCmd.points[0], pathCmd.points[1], pathCmd.points[2], pathCmd.points[3]) p1 = Kinetic.PathHelper.getPointOnQuadraticBezier(currentT, pathCmd.start.x, pathCmd.start.y, pathCmd.points[0], pathCmd.points[1], pathCmd.points[2], pathCmd.points[3]);
break; break;
} }
if (p1 !== undefined) if (p1 !== undefined) {
{ currLen = Kinetic.PathHelper.getLineLength(p0.x, p0.y, p1.x, p1.y);
currLen = that._getLineLength(p0.x, p0.y, p1.x, p1.y);
} }
if (needNewSegment) { if (needNewSegment) {
@ -248,9 +255,9 @@ Kinetic.TextPath = Kinetic.Path.extend({
pathCmd = undefined; pathCmd = undefined;
} }
} }
} };
for (var i=0; i < charArr.length; i++) { for (var i = 0; i < charArr.length; i++) {
// Find p1 such that line segment between p0 and p1 is approx. width of glyph // Find p1 such that line segment between p0 and p1 is approx. width of glyph
findSegmentToFitCharacter(charArr[i]); findSegmentToFitCharacter(charArr[i]);
@ -258,24 +265,29 @@ Kinetic.TextPath = Kinetic.Path.extend({
if (p0 === undefined || p1 === undefined) if (p0 === undefined || p1 === undefined)
break; break;
var width = this._getLineLength(p0.x, p0.y, p1.x, p1.y); var width = Kinetic.PathHelper.getLineLength(p0.x, p0.y, p1.x, p1.y);
// Note: Since glyphs are rendered one at a time, any kerning pair data built into the font will not be used. // Note: Since glyphs are rendered one at a time, any kerning pair data built into the font will not be used.
// Can foresee having a rough pair table built in that the developer can override as needed. // Can foresee having a rough pair table built in that the developer can override as needed.
var kern = 0; // placeholder for future implementation var kern = 0; // placeholder for future implementation
var midpoint = this._getPointOnLine(kern + width / 2.0, p0.x, p0.y, p1.x, p1.y); var midpoint = Kinetic.PathHelper.getPointOnLine(kern + width / 2.0, p0.x, p0.y, p1.x, p1.y);
var rotation = Math.atan2((p1.y - p0.y),(p1.x - p0.x)); var rotation = Math.atan2((p1.y - p0.y), (p1.x - p0.x));
this.glyphInfo.push({ transposeX: midpoint.x, transposeY: midpoint.y, text: charArr[i], rotation: rotation, p0:p0, p1:p1}); this.glyphInfo.push({
transposeX : midpoint.x,
transposeY : midpoint.y,
text : charArr[i],
rotation : rotation,
p0 : p0,
p1 : p1
});
p0 = p1; p0 = p1;
} }
} }
}); });
// add setters and getters // add setters and getters
Kinetic.Node.addGettersSetters(Kinetic.TextPath, ['fontFamily', 'fontSize', 'fontStyle', 'textFill', 'textStroke', 'textStrokeWidth', 'text']); Kinetic.Node.addGettersSetters(Kinetic.TextPath, ['fontFamily', 'fontSize', 'fontStyle', 'textFill', 'textStroke', 'textStrokeWidth', 'text']);

View File

@ -0,0 +1,231 @@
///////////////////////////////////////////////////////////////////////
// PathHelper
///////////////////////////////////////////////////////////////////////
Kinetic.PathHelper = {
calcLength : function (x, y, cmd, points) {
var len,
p1,
p2;
switch (cmd) {
case 'L':
return this.getLineLength(x, y, points[0], points[1]);
case 'C':
// Approximates by breaking curve into 100 line segments
len = 0.0;
p1 = this.getPointOnCubicBezier(0, x, y, points[0], points[1], points[2], points[3], points[4], points[5]);
for (t = 0.01; t <= 1; t += 0.01) {
p2 = this.getPointOnCubicBezier(t, x, y, points[0], points[1], points[2], points[3], points[4], points[5]);
len += this.getLineLength(p1.x, p1.y, p2.x, p2.y);
p1 = p2;
}
return len;
case 'Q':
// Approximates by breaking curve into 100 line segments
len = 0.0;
p1 = this.getPointOnQuadraticBezier(0, x, y, points[0], points[1], points[2], points[3]);
for (t = 0.01; t <= 1; t += 0.01) {
p2 = this.getPointOnQuadraticBezier(t, x, y, points[0], points[1], points[2], points[3]);
len += this.getLineLength(p1.x, p1.y, p2.x, p2.y);
p1 = p2;
}
return len;
case 'A':
// Approximates by breaking curve into line segments
len = 0.0;
var start = points[4]; // 4 = theta
var dTheta = points[5]; // 5 = dTheta
var end = points[4] + dTheta;
var inc = Math.PI / 180.0; // 1 degree resolution
if (Math.abs(start - end) < inc) {
inc = Math.abs(start - end);
}
// Note: for purpose of calculating arc length, not going to worry about rotating X-axis by angle psi
p1 = this.getPointOnEllipticalArc(points[0], points[1], points[2], points[3], start, 0);
if (dTheta < 0) { // clockwise
for (t = start - inc; t > end; t -= inc) {
p2 = this.getPointOnEllipticalArc(points[0], points[1], points[2], points[3], t, 0);
len += this.getLineLength(p1.x, p1.y, p2.x, p2.y);
p1 = p2;
}
} else { // counter-clockwise
for (t = start + inc; t < end; t += inc) {
p2 = this.getPointOnEllipticalArc(points[0], points[1], points[2], points[3], t, 0);
len += this.getLineLength(p1.x, p1.y, p2.x, p2.y);
p1 = p2;
}
}
p2 = this.getPointOnEllipticalArc(points[0], points[1], points[2], points[3], end, 0);
len += this.getLineLength(p1.x, p1.y, p2.x, p2.y);
return len;
}
return 0;
},
getLineLength : function (x1, y1, x2, y2) {
return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
},
getPointOnLine : function (dist, P1x, P1y, P2x, P2y, fromX, fromY) {
if (fromX === undefined) {
fromX = P1x;
}
if (fromY === undefined) {
fromY = P1y;
}
var m = (P2y - P1y) / ((P2x - P1x) + 0.00000001);
var run = Math.sqrt(dist * dist / (1 + m * m));
var rise = m * run;
var pt;
if ((fromY - P1y) / ((fromX - P1x) + 0.00000001) === m) {
pt = {
x : fromX + run,
y : fromY + rise
};
} else {
var ix,
iy;
var len = this.getLineLength(P1x, P1y, P2x, P2y);
if (len < 0.00000001) {
return undefined;
}
var u = (((fromX - P1x) * (P2x - P1x)) + ((fromY - P1y) * (P2y - P1y)));
u = u / (len * len);
ix = P1x + u * (P2x - P1x);
iy = P1y + u * (P2y - P1y);
var pRise = this.getLineLength(fromX, fromY, ix, iy);
var pRun = Math.sqrt(dist * dist - pRise * pRise);
run = Math.sqrt(pRun * pRun / (1 + m * m));
rise = m * run;
pt = {
x : ix + run,
y : iy + rise
};
}
return pt;
},
getPointOnCubicBezier : function (pct, P1x, P1y, P2x, P2y, P3x, P3y, P4x, P4y) {
function CB1(t) {
return t * t * t;
}
function CB2(t) {
return 3 * t * t * (1 - t);
}
function CB3(t) {
return 3 * t * (1 - t) * (1 - t);
}
function CB4(t) {
return (1 - t) * (1 - t) * (1 - t);
}
var x = P4x * CB1(pct) + P3x * CB2(pct) + P2x * CB3(pct) + P1x * CB4(pct);
var y = P4y * CB1(pct) + P3y * CB2(pct) + P2y * CB3(pct) + P1y * CB4(pct);
return {
x : x,
y : y
};
},
getPointOnQuadraticBezier : function (pct, P1x, P1y, P2x, P2y, P3x, P3y) {
function QB1(t) {
return t * t;
}
function QB2(t) {
return 2 * t * (1 - t);
}
function QB3(t) {
return (1 - t) * (1 - t);
}
var x = P3x * QB1(pct) + P2x * QB2(pct) + P1x * QB3(pct);
var y = P3y * QB1(pct) + P2y * QB2(pct) + P1y * QB3(pct);
return {
x : x,
y : y
};
},
getPointOnEllipticalArc : function (cx, cy, rx, ry, theta, psi) {
var cosPsi = Math.cos(psi),
sinPsi = Math.sin(psi);
var pt = {
x : rx * Math.cos(theta),
y : ry * Math.sin(theta)
};
return {
x : cx + (pt.x * cosPsi - pt.y * sinPsi),
y : cy + (pt.x * sinPsi + pt.y * cosPsi)
};
},
convertEndpointToCenterParameterization : function (x1, y1, x2, y2, fa, fs, rx, ry, psiDeg) {
// Derived from: http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes
var psi = psiDeg * (Math.PI / 180.0);
var xp = Math.cos(psi) * (x1 - x2) / 2.0 + Math.sin(psi) * (y1 - y2) / 2.0;
var yp = -1 * Math.sin(psi) * (x1 - x2) / 2.0 + Math.cos(psi) * (y1 - y2) / 2.0;
var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
if (lambda > 1) {
rx *= Math.sqrt(lambda);
ry *= Math.sqrt(lambda);
}
var f = Math.sqrt((((rx * rx) * (ry * ry)) - ((rx * rx) * (yp * yp)) - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp) + (ry * ry) * (xp * xp)));
if (fa == fs)
f *= -1;
if (isNaN(f))
f = 0;
var cxp = f * rx * yp / ry;
var cyp = f * -ry * xp / rx;
var cx = (x1 + x2) / 2.0 + Math.cos(psi) * cxp - Math.sin(psi) * cyp;
var cy = (y1 + y2) / 2.0 + Math.sin(psi) * cxp + Math.cos(psi) * cyp;
var vMag = function (v) {
return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
};
var vRatio = function (u, v) {
return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
};
var vAngle = function (u, v) {
return (u[0] * v[1] < u[1] * v[0] ? -1 : 1) * Math.acos(vRatio(u, v));
};
var theta = vAngle([1, 0], [(xp - cxp) / rx, (yp - cyp) / ry]);
var u = [(xp - cxp) / rx, (yp - cyp) / ry];
var v = [(-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry];
var dTheta = vAngle(u, v);
if (vRatio(u, v) <= -1)
dTheta = Math.PI;
if (vRatio(u, v) >= 1)
dTheta = 0;
if (fs === 0 && dTheta > 0)
dTheta = dTheta - 2 * Math.PI;
if (fs == 1 && dTheta < 0)
dTheta = dTheta + 2 * Math.PI;
return [cx, cy, rx, ry, theta, dTheta, psi, fs];
}
};

File diff suppressed because one or more lines are too long