paper.js/src/path/CompoundPath.js

106 lines
2.6 KiB
JavaScript
Raw Normal View History

2011-03-06 19:50:44 -05:00
/*
* Paper.js
*
* This file is part of Paper.js, a JavaScript Vector Graphics Library,
* based on Scriptographer.org and designed to be largely API compatible.
2011-03-07 20:41:50 -05:00
* http://paperjs.org/
2011-03-06 19:50:44 -05:00
* http://scriptographer.org/
*
2011-03-07 20:41:50 -05:00
* Distributed under the MIT license. See LICENSE file for details.
*
2011-03-06 19:50:44 -05:00
* Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
* http://lehni.org/ & http://jonathanpuckey.com/
*
2011-03-07 20:41:50 -05:00
* All rights reserved.
2011-03-06 19:50:44 -05:00
*/
var CompoundPath = this.CompoundPath = PathItem.extend({
initialize: function(items) {
this.base();
this.children = [];
if (items) {
2011-04-21 15:12:48 -04:00
for (var i = 0, l = items.length; i < l; i++)
this.appendTop(items[i]);
}
},
/**
* If this is a compound path with only one path inside,
* the path is moved outside and the compound path is erased.
* Otherwise, the compound path is returned unmodified.
*
* @return the simplified compound path.
*/
simplify: function() {
if (this.children.length == 1) {
var child = this.children[0];
child.moveAbove(this);
this.remove();
return child;
}
return this;
},
smooth: function() {
2011-04-21 15:12:48 -04:00
for (var i = 0, l = this.children.length; i < l; i++)
this.children[i].smooth();
},
draw: function(ctx, param) {
var firstChild = this.children[0];
ctx.beginPath();
param.compound = true;
2011-04-21 15:12:48 -04:00
for (var i = 0, l = this.children.length; i < l; i++)
Item.draw(this.children[i], ctx, param);
firstChild._setStyles(ctx);
var fillColor = firstChild.getFillColor(),
strokeColor = firstChild.getStrokeColor();
if (fillColor) {
ctx.fillStyle = fillColor.toCssString();
ctx.fill();
}
if (strokeColor) {
ctx.strokeStyle = strokeColor.toCssString();
ctx.stroke();
}
}
}, new function() { // Injection scope for PostScript-like drawing functions
function getCurrentPath(that) {
if (that.children.length) {
return that.children[that.children.length - 1];
} else {
2011-03-03 12:29:40 -05:00
throw new Error('Use a moveTo() command first');
}
}
var fields = {
moveTo: function() {
var path = new Path();
this.appendTop(path);
path.moveTo.apply(path, arguments);
},
moveBy: function() {
2011-04-21 15:12:48 -04:00
var point = arguments.length ? Point.read(arguments) : new Point(),
path = getCurrentPath(this),
current = path.segments[path.segments.length - 1]._point;
this.moveTo(current.add(point));
},
closePath: function() {
2011-04-30 18:22:29 -04:00
getCurrentPath(this).setClosed(true);
}
};
// Redirect all other drawing commands to the current path
Base.each(['lineTo', 'cubicCurveTo', 'quadraticCurveTo', 'curveTo',
'arcTo', 'lineBy', 'curveBy', 'arcBy'], function(key) {
fields[key] = function() {
var path = getCurrentPath(this);
path[key].apply(path, arguments);
};
});
return fields;
});