1 // ┌─────────────────────────────────────────────────────────────────────┐ \\
2 // │ "Raphaël 2.0" - JavaScript Vector Library │ \\
3 // ├─────────────────────────────────────────────────────────────────────┤ \\
4 // │ Copyright (c) 2008-2011 Dmitry Baranovskiy (http://raphaeljs.com) │ \\
5 // │ Copyright (c) 2008-2011 Sencha Labs (http://sencha.com) │ \\
6 // │ Licensed under the MIT (http://raphaeljs.com/license.html) license. │ \\
7 // └─────────────────────────────────────────────────────────────────────┘ \\
13 * Creates a canvas object on which to draw.
14 * You must do this first, as all future calls to drawing methods
15 * from this instance will be bound to this canvas.
18 - container (HTMLElement|string) DOM element or its ID which is going to be a parent for drawing surface
21 - callback (function) #optional callback function which is going to be executed in the context of newly created paper
27 - callback (function) #optional callback function which is going to be executed in the context of newly created paper
29 - all (array) (first 3 or 4 elements in the array are equal to [containerID, width, height] or [x, y, width, height]. The rest are element descriptions in format {type: type, <attributes>})
30 - callback (function) #optional callback function which is going to be executed in the context of newly created paper
32 - onReadyCallback (function) function that is going to be called on DOM ready event. You can also subscribe to this event via Eve’s “DOMLoad” event. In this case method returns `undefined`.
35 | // Each of the following examples create a canvas
36 | // that is 320px wide by 200px high.
37 | // Canvas is created at the viewport’s 10,50 coordinate.
38 | var paper = Raphael(10, 50, 320, 200);
39 | // Canvas is created at the top left corner of the #notepad element
40 | // (or its top right corner in dir="rtl" elements)
41 | var paper = Raphael(document.getElementById("notepad"), 320, 200);
43 | var paper = Raphael("notepad", 320, 200);
45 | var set = Raphael(["notepad", 320, 200, {
60 if (R.is(first, "function")) {
61 return loaded ? first() : eve.on("DOMload", first);
62 } else if (R.is(first, array)) {
64 cnv = R._engine.create[apply](R, a.splice(0, 3 + R.is(a[0], nu))),
71 elements[has](j.type) && res.push(cnv[j.type]().attr(j));
75 var args = Array.prototype.slice.call(arguments, 0);
76 if (R.is(args[args.length - 1], "function")) {
78 return loaded ? f.call(R._engine.create[apply](R, args)) : eve.on("DOMload", function () {
79 f.call(R._engine.create[apply](R, args));
82 return R._engine.create[apply](R, arguments);
90 elements = {circle: 1, rect: 1, path: 1, ellipse: 1, text: 1, image: 1},
91 formatrg = /\{(\d+)\}/g,
93 has = "hasOwnProperty",
99 was: Object.prototype[has].call(g.win, "Raphael"),
102 Paper = function () {},
104 appendChild = "appendChild",
107 supportsTouch = "createTouch" in g.doc,
112 events = "click dblclick mousedown mousemove mouseout mouseover mouseup touchstart touchmove touchend touchcancel".split(S),
114 mousedown: "touchstart",
115 mousemove: "touchmove",
118 lowerCase = Str.prototype.toLowerCase,
128 toString = "toString",
130 objectToString = Object.prototype.toString,
133 ISURL = R._ISURL = /^url\(['"]?([^\)]+?)['"]?\)$/i,
134 colourRegExp = /^\s*((#[a-f\d]{6})|(#[a-f\d]{3})|rgba?\(\s*([\d\.]+%?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\)|hsba?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\)|hsla?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\))\s*$/i,
135 isnan = {"NaN": 1, "Infinity": 1, "-Infinity": 1},
136 bezierrg = /^(?:cubic-)?bezier\(([^,]+),([^,]+),([^,]+),([^\)]+)\)/,
138 setAttribute = "setAttribute",
139 toFloat = parseFloat,
141 ms = " progid:DXImageTransform.Microsoft",
142 upperCase = Str.prototype.toUpperCase,
143 availableAttrs = R._availableAttrs = {
145 "arrow-start": "none",
147 "clip-rect": "0 0 1e9 1e9",
153 font: '10px "Arial"',
154 "font-family": '"Arial"',
156 "font-style": "normal",
160 href: "http://raphaeljs.com/",
168 "stroke-dasharray": "",
169 "stroke-linecap": "butt",
170 "stroke-linejoin": "butt",
171 "stroke-miterlimit": 0,
175 "text-anchor": "middle",
182 availableAnimAttrs = R._availableAnimAttrs = {
197 "stroke-opacity": nu,
199 transform: "transform",
204 commaSpaces = /\s*,\s*/,
205 hsrg = {hs: 1, rg: 1},
206 p2s = /,?([achlmqrstvxz]),?/gi,
207 pathCommand = /([achlmqstvz])[\s,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?\s*,?\s*)+)/ig,
208 tCommand = /([rstm])[\s,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?\s*,?\s*)+)/ig,
209 pathValues = /(-?\d*\.?\d*(?:e[\-+]?\d+)?)\s*,?\s*/ig,
210 radial_gradient = R._radial_gradient = /^r(?:\(([^,]+?)\s*,\s*([^\)]+?)\))?/,
212 sortByKey = function (a, b) {
213 return a.key - b.key;
215 sortByNumber = function (a, b) {
218 fun = function () {},
219 pipe = function (x) {
222 rectPath = R._rectPath = function (x, y, w, h, r) {
224 return [["M", x + r, y], ["l", w - r * 2, 0], ["a", r, r, 0, 0, 1, r, r], ["l", 0, h - r * 2], ["a", r, r, 0, 0, 1, -r, r], ["l", r * 2 - w, 0], ["a", r, r, 0, 0, 1, -r, -r], ["l", 0, r * 2 - h], ["a", r, r, 0, 0, 1, r, -r], ["z"]];
226 return [["M", x, y], ["l", w, 0], ["l", 0, h], ["l", -w, 0], ["z"]];
228 ellipsePath = function (x, y, rx, ry) {
232 return [["M", x, y], ["m", 0, -ry], ["a", rx, ry, 0, 1, 1, 0, 2 * ry], ["a", rx, ry, 0, 1, 1, 0, -2 * ry], ["z"]];
234 getPath = R._getPath = {
235 path: function (el) {
236 return el.attr("path");
238 circle: function (el) {
240 return ellipsePath(a.cx, a.cy, a.r);
242 ellipse: function (el) {
244 return ellipsePath(a.cx, a.cy, a.rx, a.ry);
246 rect: function (el) {
248 return rectPath(a.x, a.y, a.width, a.height, a.r);
250 image: function (el) {
252 return rectPath(a.x, a.y, a.width, a.height);
254 text: function (el) {
255 var bbox = el._getBBox();
256 return rectPath(bbox.x, bbox.y, bbox.width, bbox.height);
259 mapPath = function (path, matrix) {
263 var x, y, i, j, pathi;
264 path = path2curve(path);
265 for (i = 0, ii = path.length; i < ii; i++) {
267 for (j = 1, jj = pathi.length; j < jj; j += 2) {
268 x = matrix.x(pathi[j], pathi[j + 1]);
269 y = matrix.y(pathi[j], pathi[j + 1]);
280 [ property (string) ]
282 * Can be “SVG”, “VML” or empty, depending on browser support.
284 R.type = (g.win.SVGAngle || g.doc.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") ? "SVG" : "VML");
285 if (R.type == "VML") {
286 var d = g.doc.createElement("div"),
288 d.innerHTML = '<v:shape adj="1"/>';
290 b.style.behavior = "url(#default#VML)";
291 if (!(b && typeof b.adj == "object")) {
298 [ property (boolean) ]
300 * `true` if browser supports SVG.
304 [ property (boolean) ]
306 * `true` if browser supports VML.
308 R.svg = !(R.vml = R.type == "VML");
312 [ property (object) ]
314 * You can add your own method to the canvas. For example if you want to draw a pie chart,
315 * you can create your own pie chart function and ship it as a Raphaël plugin. To do this
316 * you need to extend the `Raphael.fn` object. Please note that you can create your own namespaces
317 * inside the `fn` object — methods will be run in the context of canvas anyway. You should alter
318 * the `fn` object before a Raphaël instance is created, otherwise it will take no effect.
320 | Raphael.fn.arrow = function (x1, y1, x2, y2, size) {
321 | return this.path( ... );
323 | // or create namespace
324 | Raphael.fn.mystuff = {
325 | arrow: function () {…},
326 | star: function () {…},
329 | var paper = Raphael(10, 10, 630, 480);
331 | paper.arrow(10, 10, 30, 30, 5).attr({fill: "#f00"});
332 | paper.mystuff.arrow();
333 | paper.mystuff.star();
335 R.fn = paperproto = Paper.prototype = R.prototype;
337 * Paper.customAttributes
338 [ property (object) ]
340 * If you have a set of attributes that you would like to represent
341 * as a function of some number you can do it easily with custom attributes:
343 | paper.customAttributes.hue = function (num) {
345 | return {fill: "hsb(" + num + ", .75, 1)"};
347 | // Custom attribute “hue” will change fill
348 | // to be given hue with fixed saturation and brightness.
349 | // Now you can use it like this:
350 | var c = paper.circle(10, 10, 10).attr({hue: .45});
351 | // or even like this:
352 | c.animate({hue: 1}, 1e3);
354 | // You could also create custom attribute
355 | // with multiple parameters:
356 | paper.customAttributes.hsb = function (h, s, b) {
357 | return {fill: "hsb(" + [h, s, b].join(",") + ")"};
359 | c.attr({hsb: ".5 .8 1"});
360 | c.animate({hsb: "1 0 .5"}, 1e3);
362 paperproto.customAttributes = {};
369 * Handfull replacement for `typeof` operator.
371 - o (…) any object or primitive
372 - type (string) name of the type, i.e. “string”, “function”, “number”, etc.
373 = (boolean) is given value is of given type
375 R.is = function (o, type) {
376 type = lowerCase.call(type);
377 if (type == "finite") {
378 return !isnan[has](+o);
380 if (type == "array") {
381 return o instanceof Array;
383 return (type == "null" && o === null) ||
384 (type == typeof o) ||
385 (type == "object" && o === Object(o)) ||
386 (type == "array" && Array.isArray && Array.isArray(o)) ||
387 objectToString.call(o).slice(8, -1).toLowerCase() == type;
393 * Returns angle between two or three points
395 - x1 (number) x coord of first point
396 - y1 (number) y coord of first point
397 - x2 (number) x coord of second point
398 - y2 (number) y coord of second point
399 - x3 (number) #optional x coord of third point
400 - y3 (number) #optional y coord of third point
401 = (number) angle in degrees.
403 R.angle = function (x1, y1, x2, y2, x3, y3) {
410 return (180 + math.atan2(-y, -x) * 180 / PI + 360) % 360;
412 return R.angle(x1, y1, x3, y3) - R.angle(x2, y2, x3, y3);
419 * Transform angle to radians
421 - deg (number) angle in degrees
422 = (number) angle in radians.
424 R.rad = function (deg) {
425 return deg % 360 * PI / 180;
431 * Transform angle to degrees
433 - deg (number) angle in radians
434 = (number) angle in degrees.
436 R.deg = function (rad) {
437 return rad * 180 / PI % 360;
443 * Snaps given value to given grid.
445 - values (array|number) given array of values or step of the grid
446 - value (number) value to adjust
447 - tolerance (number) #optional tolerance for snapping. Default is `10`.
448 = (number) adjusted value.
450 R.snapTo = function (values, value, tolerance) {
451 tolerance = R.is(tolerance, "finite") ? tolerance : 10;
452 if (R.is(values, array)) {
453 var i = values.length;
454 while (i--) if (abs(values[i] - value) <= tolerance) {
459 var rem = value % values;
460 if (rem < tolerance) {
463 if (rem > values - tolerance) {
464 return value - rem + values;
470 var createUUID = R._createUUID = (function (uuidRegEx, uuidReplacer) {
472 return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(uuidRegEx, uuidReplacer).toUpperCase();
474 })(/[xy]/g, function (c) {
475 var r = math.random() * 16 | 0,
476 v = c == "x" ? r : (r & 3 | 8);
477 return v.toString(16);
484 * Used when you need to draw in `<iframe>`. Switched window to the iframe one.
486 - newwin (window) new window object
488 R.setWindow = function (newwin) {
489 eve("setWindow", R, g.win, newwin);
491 g.doc = g.win.document;
497 var toHex = function (color) {
499 // http://dean.edwards.name/weblog/2009/10/convert-any-colour-value-to-hex-in-msie/
500 var trim = /^\s+|\s+$/g;
503 var docum = new ActiveXObject("htmlfile");
504 docum.write("<body>");
508 bod = createPopup().document.body;
510 var range = bod.createTextRange();
511 toHex = cacher(function (color) {
513 bod.style.color = Str(color).replace(trim, E);
514 var value = range.queryCommandValue("ForeColor");
515 value = ((value & 255) << 16) | (value & 65280) | ((value & 16711680) >>> 16);
516 return "#" + ("000000" + value.toString(16)).slice(-6);
522 var i = g.doc.createElement("i");
523 i.title = "Rapha\xebl Colour Picker";
524 i.style.display = "none";
525 g.doc.body.appendChild(i);
526 toHex = cacher(function (color) {
527 i.style.color = color;
528 return g.doc.defaultView.getComputedStyle(i, E).getPropertyValue("color");
533 hsbtoString = function () {
534 return "hsb(" + [this.h, this.s, this.b] + ")";
536 hsltoString = function () {
537 return "hsl(" + [this.h, this.s, this.l] + ")";
539 rgbtoString = function () {
542 prepareRGB = function (r, g, b) {
543 if (g == null && R.is(r, "object") && "r" in r && "g" in r && "b" in r) {
548 if (g == null && R.is(r, string)) {
549 var clr = R.getRGB(r);
554 if (r > 1 || g > 1 || b > 1) {
562 packageRGB = function (r, g, b, o) {
571 toString: rgbtoString
573 R.is(o, "finite") && (rgb.opacity = o);
581 * Parses the color string and returns object with all values for the given color.
583 - clr (string) color string in one of the supported formats (see @Raphael.getRGB)
584 = (object) Combined RGB & HSB object in format:
589 o hex (string) color in HTML/CSS format: #••••••,
590 o error (boolean) `true` if string can’t be parsed,
592 o s (number) saturation,
593 o v (number) value (brightness),
594 o l (number) lightness
597 R.color = function (clr) {
599 if (R.is(clr, "object") && "h" in clr && "s" in clr && "b" in clr) {
600 rgb = R.hsb2rgb(clr);
605 } else if (R.is(clr, "object") && "h" in clr && "s" in clr && "l" in clr) {
606 rgb = R.hsl2rgb(clr);
612 if (R.is(clr, "string")) {
615 if (R.is(clr, "object") && "r" in clr && "g" in clr && "b" in clr) {
616 rgb = R.rgb2hsl(clr);
620 rgb = R.rgb2hsb(clr);
624 crl.r = clr.g = clr.b = clr.h = clr.s = clr.v = clr.l = -1;
627 clr.toString = rgbtoString;
634 * Converts HSB values to RGB object.
637 - s (number) saturation
638 - v (number) value or brightness
639 = (object) RGB object in format:
644 o hex (string) color in HTML/CSS format: #••••••
647 R.hsb2rgb = function (h, s, v, o) {
648 if (this.is(h, "object") && "h" in h && "s" in h && "b" in h) {
658 X = C * (1 - abs(h % 2 - 1));
662 R += [C, X, 0, 0, X, C][h];
663 G += [X, C, C, X, 0, 0][h];
664 B += [0, 0, X, C, C, X][h];
665 return packageRGB(R, G, B, o);
671 * Converts HSL values to RGB object.
674 - s (number) saturation
675 - l (number) luminosity
676 = (object) RGB object in format:
681 o hex (string) color in HTML/CSS format: #••••••
684 R.hsl2rgb = function (h, s, l, o) {
685 if (this.is(h, "object") && "h" in h && "s" in h && "l" in h) {
690 if (h > 1 || s > 1 || l > 1) {
698 C = 2 * s * (l < .5 ? l : 1 - l);
699 X = C * (1 - abs(h % 2 - 1));
700 R = G = B = l - C / 2;
703 R += [C, X, 0, 0, X, C][h];
704 G += [X, C, C, X, 0, 0][h];
705 B += [0, 0, X, C, C, X][h];
706 return packageRGB(R, G, B, o);
712 * Converts RGB values to HSB object.
717 = (object) HSB object in format:
720 o s (number) saturation
721 o b (number) brightness
724 R.rgb2hsb = function (r, g, b) {
725 b = prepareRGB(r, g, b);
732 C = V - mmin(r, g, b);
734 V == r ? (g - b) / C :
735 V == g ? (b - r) / C + 2 :
738 H = ((H + 360) % 6) * 60 / 360;
739 S = C == 0 ? 0 : C / V;
740 return {h: H, s: S, b: V, toString: hsbtoString};
746 * Converts RGB values to HSL object.
751 = (object) HSL object in format:
754 o s (number) saturation
755 o l (number) luminosity
758 R.rgb2hsl = function (r, g, b) {
759 b = prepareRGB(r, g, b);
764 var H, S, L, M, m, C;
769 M == r ? (g - b) / C :
770 M == g ? (b - r) / C + 2 :
772 H = ((H + 360) % 6) * 60 / 360;
775 L < .5 ? C / (2 * L) :
777 return {h: H, s: S, l: L, toString: hsltoString};
779 R._path2string = function () {
780 return this.join(",").replace(p2s, "$1");
782 function repush(array, item) {
783 for (var i = 0, ii = array.length; i < ii; i++) if (array[i] === item) {
784 return array.push(array.splice(i, 1)[0]);
787 function cacher(f, scope, postprocessor) {
789 var arg = Array.prototype.slice.call(arguments, 0),
790 args = arg.join("\u2400"),
791 cache = newf.cache = newf.cache || {},
792 count = newf.count = newf.count || [];
793 if (cache[has](args)) {
795 return postprocessor ? postprocessor(cache[args]) : cache[args];
797 count.length >= 1e3 && delete cache[count.shift()];
799 cache[args] = f[apply](scope, arg);
800 return postprocessor ? postprocessor(cache[args]) : cache[args];
805 var preload = R._preload = function (src, f) {
806 var img = g.doc.createElement("img");
807 img.style.cssText = "position:absolute;left:-9999em;top-9999em";
808 img.onload = function () {
811 g.doc.body.removeChild(this);
813 img.onerror = function () {
814 g.doc.body.removeChild(this);
816 g.doc.body.appendChild(img);
820 function clrToString() {
828 * Parses colour string as RGB object
830 - colour (string) colour string in one of formats:
832 # <li>Colour name (“<code>red</code>”, “<code>green</code>”, “<code>cornflowerblue</code>”, etc)</li>
833 # <li>#••• — shortened HTML colour: (“<code>#000</code>”, “<code>#fc0</code>”, etc)</li>
834 # <li>#•••••• — full length HTML colour: (“<code>#000000</code>”, “<code>#bd2300</code>”)</li>
835 # <li>rgb(•••, •••, •••) — red, green and blue channels’ values: (“<code>rgb(200, 100, 0)</code>”)</li>
836 # <li>rgb(•••%, •••%, •••%) — same as above, but in %: (“<code>rgb(100%, 175%, 0%)</code>”)</li>
837 # <li>hsb(•••, •••, •••) — hue, saturation and brightness values: (“<code>hsb(0.5, 0.25, 1)</code>”)</li>
838 # <li>hsb(•••%, •••%, •••%) — same as above, but in %</li>
839 # <li>hsl(•••, •••, •••) — same as hsb</li>
840 # <li>hsl(•••%, •••%, •••%) — same as hsb</li>
842 = (object) RGB object in format:
847 o hex (string) color in HTML/CSS format: #••••••,
848 o error (boolean) true if string can’t be parsed
851 R.getRGB = cacher(function (colour) {
852 if (!colour || !!((colour = Str(colour)).indexOf("-") + 1)) {
853 return {r: -1, g: -1, b: -1, hex: "none", error: 1, toString: clrToString};
855 if (colour == "none") {
856 return {r: -1, g: -1, b: -1, hex: "none", toString: clrToString};
858 !(hsrg[has](colour.toLowerCase().substring(0, 2)) || colour.charAt() == "#") && (colour = toHex(colour));
866 rgb = colour.match(colourRegExp);
869 blue = toInt(rgb[2].substring(5), 16);
870 green = toInt(rgb[2].substring(3, 5), 16);
871 red = toInt(rgb[2].substring(1, 3), 16);
874 blue = toInt((t = rgb[3].charAt(3)) + t, 16);
875 green = toInt((t = rgb[3].charAt(2)) + t, 16);
876 red = toInt((t = rgb[3].charAt(1)) + t, 16);
879 values = rgb[4].split(commaSpaces);
880 red = toFloat(values[0]);
881 values[0].slice(-1) == "%" && (red *= 2.55);
882 green = toFloat(values[1]);
883 values[1].slice(-1) == "%" && (green *= 2.55);
884 blue = toFloat(values[2]);
885 values[2].slice(-1) == "%" && (blue *= 2.55);
886 rgb[1].toLowerCase().slice(0, 4) == "rgba" && (opacity = toFloat(values[3]));
887 values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
890 values = rgb[5].split(commaSpaces);
891 red = toFloat(values[0]);
892 values[0].slice(-1) == "%" && (red *= 2.55);
893 green = toFloat(values[1]);
894 values[1].slice(-1) == "%" && (green *= 2.55);
895 blue = toFloat(values[2]);
896 values[2].slice(-1) == "%" && (blue *= 2.55);
897 (values[0].slice(-3) == "deg" || values[0].slice(-1) == "\xb0") && (red /= 360);
898 rgb[1].toLowerCase().slice(0, 4) == "hsba" && (opacity = toFloat(values[3]));
899 values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
900 return R.hsb2rgb(red, green, blue, opacity);
903 values = rgb[6].split(commaSpaces);
904 red = toFloat(values[0]);
905 values[0].slice(-1) == "%" && (red *= 2.55);
906 green = toFloat(values[1]);
907 values[1].slice(-1) == "%" && (green *= 2.55);
908 blue = toFloat(values[2]);
909 values[2].slice(-1) == "%" && (blue *= 2.55);
910 (values[0].slice(-3) == "deg" || values[0].slice(-1) == "\xb0") && (red /= 360);
911 rgb[1].toLowerCase().slice(0, 4) == "hsla" && (opacity = toFloat(values[3]));
912 values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
913 return R.hsl2rgb(red, green, blue, opacity);
915 rgb = {r: red, g: green, b: blue, toString: clrToString};
916 rgb.hex = "#" + (16777216 | blue | (green << 8) | (red << 16)).toString(16).slice(1);
917 R.is(opacity, "finite") && (rgb.opacity = opacity);
920 return {r: -1, g: -1, b: -1, hex: "none", error: 1, toString: clrToString};
926 * Converts HSB values to hex representation of the colour.
929 - s (number) saturation
930 - b (number) value or brightness
931 = (string) hex representation of the colour.
933 R.hsb = cacher(function (h, s, b) {
934 return R.hsb2rgb(h, s, b).hex;
940 * Converts HSL values to hex representation of the colour.
943 - s (number) saturation
944 - l (number) luminosity
945 = (string) hex representation of the colour.
947 R.hsl = cacher(function (h, s, l) {
948 return R.hsl2rgb(h, s, l).hex;
954 * Converts RGB values to hex representation of the colour.
959 = (string) hex representation of the colour.
961 R.rgb = cacher(function (r, g, b) {
962 return "#" + (16777216 | b | (g << 8) | (r << 16)).toString(16).slice(1);
968 * On each call returns next colour in the spectrum. To reset it back to red call @Raphael.getColor.reset
970 - value (number) #optional brightness, default is `0.75`
971 = (string) hex representation of the colour.
973 R.getColor = function (value) {
974 var start = this.getColor.start = this.getColor.start || {h: 0, s: 1, b: value || .75},
975 rgb = this.hsb2rgb(start.h, start.s, start.b);
980 start.s <= 0 && (this.getColor.start = {h: 0, s: 1, b: start.b});
985 * Raphael.getColor.reset
988 * Resets spectrum position for @Raphael.getColor back to red.
990 R.getColor.reset = function () {
995 * Raphael.parsePathString
1000 * Parses given path string into an array of arrays of path segments.
1002 - pathString (string|array) path string or array of segments (in the last case it will be returned straight away)
1003 = (array) array of segments.
1005 R.parsePathString = cacher(function (pathString) {
1009 var paramCounts = {a: 7, c: 6, h: 1, l: 2, m: 2, q: 4, s: 4, t: 2, v: 1, z: 0},
1011 if (R.is(pathString, array) && R.is(pathString[0], array)) { // rough assumption
1012 data = pathClone(pathString);
1015 Str(pathString).replace(pathCommand, function (a, b, c) {
1017 name = lowerCase.call(b);
1018 c.replace(pathValues, function (a, b) {
1019 b && params.push(+b);
1021 if (name == "m" && params.length > 2) {
1022 data.push([b][concat](params.splice(0, 2)));
1024 b = b == "m" ? "l" : "L";
1026 while (params.length >= paramCounts[name]) {
1027 data.push([b][concat](params.splice(0, paramCounts[name])));
1028 if (!paramCounts[name]) {
1034 data.toString = R._path2string;
1038 * Raphael.parseTransformString
1043 * Parses given path string into an array of transformations.
1045 - TString (string|array) transform string or array of transformations (in the last case it will be returned straight away)
1046 = (array) array of transformations.
1048 R.parseTransformString = cacher(function (TString) {
1052 var paramCounts = {r: 3, s: 4, t: 2, m: 6},
1054 if (R.is(TString, array) && R.is(TString[0], array)) { // rough assumption
1055 data = pathClone(TString);
1058 Str(TString).replace(tCommand, function (a, b, c) {
1060 name = lowerCase.call(b);
1061 c.replace(pathValues, function (a, b) {
1062 b && params.push(+b);
1064 data.push([name][concat](params));
1067 data.toString = R._path2string;
1071 * Raphael.findDotsAtSegment
1076 * Find dot coordinates on the given cubic bezier curve at the given t.
1078 - p1x (number) x of the first point of the curve
1079 - p1y (number) y of the first point of the curve
1080 - c1x (number) x of the first anchor of the curve
1081 - c1y (number) y of the first anchor of the curve
1082 - c2x (number) x of the second anchor of the curve
1083 - c2y (number) y of the second anchor of the curve
1084 - p2x (number) x of the second point of the curve
1085 - p2y (number) y of the second point of the curve
1086 - t (number) position on the curve (0..1)
1087 = (object) point information in format:
1089 o x: (number) x coordinate of the point
1090 o y: (number) y coordinate of the point
1092 o x: (number) x coordinate of the left anchor
1093 o y: (number) y coordinate of the left anchor
1096 o x: (number) x coordinate of the right anchor
1097 o y: (number) y coordinate of the right anchor
1100 o x: (number) x coordinate of the start of the curve
1101 o y: (number) y coordinate of the start of the curve
1104 o x: (number) x coordinate of the end of the curve
1105 o y: (number) y coordinate of the end of the curve
1107 o alpha: (number) angle of the curve derivative at the point
1110 R.findDotsAtSegment = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) {
1116 x = t13 * p1x + t12 * 3 * t * c1x + t1 * 3 * t * t * c2x + t3 * p2x,
1117 y = t13 * p1y + t12 * 3 * t * c1y + t1 * 3 * t * t * c2y + t3 * p2y,
1118 mx = p1x + 2 * t * (c1x - p1x) + t2 * (c2x - 2 * c1x + p1x),
1119 my = p1y + 2 * t * (c1y - p1y) + t2 * (c2y - 2 * c1y + p1y),
1120 nx = c1x + 2 * t * (c2x - c1x) + t2 * (p2x - 2 * c2x + c1x),
1121 ny = c1y + 2 * t * (c2y - c1y) + t2 * (p2y - 2 * c2y + c1y),
1122 ax = t1 * p1x + t * c1x,
1123 ay = t1 * p1y + t * c1y,
1124 cx = t1 * c2x + t * p2x,
1125 cy = t1 * c2y + t * p2y,
1126 alpha = (90 - math.atan2(mx - nx, my - ny) * 180 / PI);
1127 (mx > nx || my < ny) && (alpha += 180);
1133 start: {x: ax, y: ay},
1134 end: {x: cx, y: cy},
1138 var pathDimensions = cacher(function (path) {
1140 return {x: 0, y: 0, width: 0, height: 0};
1142 path = path2curve(path);
1148 for (var i = 0, ii = path.length; i < ii; i++) {
1156 var dim = curveDim(x, y, p[1], p[2], p[3], p[4], p[5], p[6]);
1157 X = X[concat](dim.min.x, dim.max.x);
1158 Y = Y[concat](dim.min.y, dim.max.y);
1163 var xmin = mmin[apply](0, X),
1164 ymin = mmin[apply](0, Y);
1168 width: mmax[apply](0, X) - xmin,
1169 height: mmax[apply](0, Y) - ymin
1171 }, null, function (o) {
1179 pathClone = function (pathArray) {
1181 if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) { // rough assumption
1182 pathArray = R.parsePathString(pathArray);
1184 for (var i = 0, ii = pathArray.length; i < ii; i++) {
1186 for (var j = 0, jj = pathArray[i].length; j < jj; j++) {
1187 res[i][j] = pathArray[i][j];
1190 res.toString = R._path2string;
1193 pathToRelative = R._pathToRelative = cacher(function (pathArray) {
1194 if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) { // rough assumption
1195 pathArray = R.parsePathString(pathArray);
1203 if (pathArray[0][0] == "M") {
1204 x = pathArray[0][1];
1205 y = pathArray[0][2];
1209 res.push(["M", x, y]);
1211 for (var i = start, ii = pathArray.length; i < ii; i++) {
1212 var r = res[i] = [],
1214 if (pa[0] != lowerCase.call(pa[0])) {
1215 r[0] = lowerCase.call(pa[0]);
1223 r[6] = +(pa[6] - x).toFixed(3);
1224 r[7] = +(pa[7] - y).toFixed(3);
1227 r[1] = +(pa[1] - y).toFixed(3);
1233 for (var j = 1, jj = pa.length; j < jj; j++) {
1234 r[j] = +(pa[j] - ((j % 2) ? x : y)).toFixed(3);
1243 for (var k = 0, kk = pa.length; k < kk; k++) {
1247 var len = res[i].length;
1248 switch (res[i][0]) {
1254 x += +res[i][len - 1];
1257 y += +res[i][len - 1];
1260 x += +res[i][len - 2];
1261 y += +res[i][len - 1];
1264 res.toString = R._path2string;
1267 pathToAbsolute = R._pathToAbsolute = cacher(function (pathArray) {
1268 if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) { // rough assumption
1269 pathArray = R.parsePathString(pathArray);
1271 if (!pathArray || !pathArray.length) {
1272 return [["M", 0, 0]];
1280 if (pathArray[0][0] == "M") {
1281 x = +pathArray[0][1];
1282 y = +pathArray[0][2];
1286 res[0] = ["M", x, y];
1288 for (var i = start, ii = pathArray.length; i < ii; i++) {
1289 var r = res[i] = [],
1291 if (pa[0] != upperCase.call(pa[0])) {
1292 r[0] = upperCase.call(pa[0]);
1300 r[6] = +(pa[6] + x);
1301 r[7] = +(pa[7] + y);
1313 for (var j = 1, jj = pa.length; j < jj; j++) {
1314 r[j] = +pa[j] + ((j % 2) ? x : y);
1318 for (var k = 0, kk = pa.length; k < kk; k++) {
1334 mx = res[i][res[i].length - 2];
1335 my = res[i][res[i].length - 1];
1337 x = res[i][res[i].length - 2];
1338 y = res[i][res[i].length - 1];
1341 res.toString = R._path2string;
1343 }, null, pathClone),
1344 l2c = function (x1, y1, x2, y2) {
1345 return [x1, y1, x2, y2, x2, y2];
1347 q2c = function (x1, y1, ax, ay, x2, y2) {
1351 _13 * x1 + _23 * ax,
1352 _13 * y1 + _23 * ay,
1353 _13 * x2 + _23 * ax,
1354 _13 * y2 + _23 * ay,
1359 a2c = function (x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursive) {
1360 // for more information of where this math came from visit:
1361 // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
1362 var _120 = PI * 120 / 180,
1363 rad = PI / 180 * (+angle || 0),
1366 rotate = cacher(function (x, y, rad) {
1367 var X = x * math.cos(rad) - y * math.sin(rad),
1368 Y = x * math.sin(rad) + y * math.cos(rad);
1369 return {x: X, y: Y};
1372 xy = rotate(x1, y1, -rad);
1375 xy = rotate(x2, y2, -rad);
1378 var cos = math.cos(PI / 180 * angle),
1379 sin = math.sin(PI / 180 * angle),
1382 var h = (x * x) / (rx * rx) + (y * y) / (ry * ry);
1390 k = (large_arc_flag == sweep_flag ? -1 : 1) *
1391 math.sqrt(abs((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x))),
1392 cx = k * rx * y / ry + (x1 + x2) / 2,
1393 cy = k * -ry * x / rx + (y1 + y2) / 2,
1394 f1 = math.asin(((y1 - cy) / ry).toFixed(9)),
1395 f2 = math.asin(((y2 - cy) / ry).toFixed(9));
1397 f1 = x1 < cx ? PI - f1 : f1;
1398 f2 = x2 < cx ? PI - f2 : f2;
1399 f1 < 0 && (f1 = PI * 2 + f1);
1400 f2 < 0 && (f2 = PI * 2 + f2);
1401 if (sweep_flag && f1 > f2) {
1404 if (!sweep_flag && f2 > f1) {
1414 if (abs(df) > _120) {
1418 f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1);
1419 x2 = cx + rx * math.cos(f2);
1420 y2 = cy + ry * math.sin(f2);
1421 res = a2c(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [f2, f2old, cx, cy]);
1424 var c1 = math.cos(f1),
1428 t = math.tan(df / 4),
1429 hx = 4 / 3 * rx * t,
1430 hy = 4 / 3 * ry * t,
1432 m2 = [x1 + hx * s1, y1 - hy * c1],
1433 m3 = [x2 + hx * s2, y2 - hy * c2],
1435 m2[0] = 2 * m1[0] - m2[0];
1436 m2[1] = 2 * m1[1] - m2[1];
1438 return [m2, m3, m4][concat](res);
1440 res = [m2, m3, m4][concat](res).join().split(",");
1442 for (var i = 0, ii = res.length; i < ii; i++) {
1443 newres[i] = i % 2 ? rotate(res[i - 1], res[i], rad).y : rotate(res[i], res[i + 1], rad).x;
1448 findDotAtSegment = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) {
1451 x: pow(t1, 3) * p1x + pow(t1, 2) * 3 * t * c1x + t1 * 3 * t * t * c2x + pow(t, 3) * p2x,
1452 y: pow(t1, 3) * p1y + pow(t1, 2) * 3 * t * c1y + t1 * 3 * t * t * c2y + pow(t, 3) * p2y
1455 curveDim = cacher(function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) {
1456 var a = (c2x - 2 * c1x + p1x) - (p2x - 2 * c2x + c1x),
1457 b = 2 * (c1x - p1x) - 2 * (c2x - c1x),
1459 t1 = (-b + math.sqrt(b * b - 4 * a * c)) / 2 / a,
1460 t2 = (-b - math.sqrt(b * b - 4 * a * c)) / 2 / a,
1464 abs(t1) > "1e12" && (t1 = .5);
1465 abs(t2) > "1e12" && (t2 = .5);
1466 if (t1 > 0 && t1 < 1) {
1467 dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t1);
1471 if (t2 > 0 && t2 < 1) {
1472 dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t2);
1476 a = (c2y - 2 * c1y + p1y) - (p2y - 2 * c2y + c1y);
1477 b = 2 * (c1y - p1y) - 2 * (c2y - c1y);
1479 t1 = (-b + math.sqrt(b * b - 4 * a * c)) / 2 / a;
1480 t2 = (-b - math.sqrt(b * b - 4 * a * c)) / 2 / a;
1481 abs(t1) > "1e12" && (t1 = .5);
1482 abs(t2) > "1e12" && (t2 = .5);
1483 if (t1 > 0 && t1 < 1) {
1484 dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t1);
1488 if (t2 > 0 && t2 < 1) {
1489 dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t2);
1494 min: {x: mmin[apply](0, x), y: mmin[apply](0, y)},
1495 max: {x: mmax[apply](0, x), y: mmax[apply](0, y)}
1498 path2curve = R._path2curve = cacher(function (path, path2) {
1499 var p = pathToAbsolute(path),
1500 p2 = path2 && pathToAbsolute(path2),
1501 attrs = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null},
1502 attrs2 = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null},
1503 processPath = function (path, d) {
1506 return ["C", d.x, d.y, d.x, d.y, d.x, d.y];
1508 !(path[0] in {T:1, Q:1}) && (d.qx = d.qy = null);
1515 path = ["C"][concat](a2c[apply](0, [d.x, d.y][concat](path.slice(1))));
1518 nx = d.x + (d.x - (d.bx || d.x));
1519 ny = d.y + (d.y - (d.by || d.y));
1520 path = ["C", nx, ny][concat](path.slice(1));
1523 d.qx = d.x + (d.x - (d.qx || d.x));
1524 d.qy = d.y + (d.y - (d.qy || d.y));
1525 path = ["C"][concat](q2c(d.x, d.y, d.qx, d.qy, path[1], path[2]));
1530 path = ["C"][concat](q2c(d.x, d.y, path[1], path[2], path[3], path[4]));
1533 path = ["C"][concat](l2c(d.x, d.y, path[1], path[2]));
1536 path = ["C"][concat](l2c(d.x, d.y, path[1], d.y));
1539 path = ["C"][concat](l2c(d.x, d.y, d.x, path[1]));
1542 path = ["C"][concat](l2c(d.x, d.y, d.X, d.Y));
1547 fixArc = function (pp, i) {
1548 if (pp[i].length > 7) {
1552 pp.splice(i++, 0, ["C"][concat](pi.splice(0, 6)));
1555 ii = mmax(p.length, p2 && p2.length || 0);
1558 fixM = function (path1, path2, a1, a2, i) {
1559 if (path1 && path2 && path1[i][0] == "M" && path2[i][0] != "M") {
1560 path2.splice(i, 0, ["M", a2.x, a2.y]);
1565 ii = mmax(p.length, p2 && p2.length || 0);
1568 for (var i = 0, ii = mmax(p.length, p2 && p2.length || 0); i < ii; i++) {
1569 p[i] = processPath(p[i], attrs);
1571 p2 && (p2[i] = processPath(p2[i], attrs2));
1572 p2 && fixArc(p2, i);
1573 fixM(p, p2, attrs, attrs2, i);
1574 fixM(p2, p, attrs2, attrs, i);
1577 seglen = seg.length,
1578 seg2len = p2 && seg2.length;
1579 attrs.x = seg[seglen - 2];
1580 attrs.y = seg[seglen - 1];
1581 attrs.bx = toFloat(seg[seglen - 4]) || attrs.x;
1582 attrs.by = toFloat(seg[seglen - 3]) || attrs.y;
1583 attrs2.bx = p2 && (toFloat(seg2[seg2len - 4]) || attrs2.x);
1584 attrs2.by = p2 && (toFloat(seg2[seg2len - 3]) || attrs2.y);
1585 attrs2.x = p2 && seg2[seg2len - 2];
1586 attrs2.y = p2 && seg2[seg2len - 1];
1588 return p2 ? [p, p2] : p;
1589 }, null, pathClone),
1590 parseDots = R._parseDots = cacher(function (gradient) {
1592 for (var i = 0, ii = gradient.length; i < ii; i++) {
1594 par = gradient[i].match(/^([^:]*):?([\d\.]*)/);
1595 dot.color = R.getRGB(par[1]);
1596 if (dot.color.error) {
1599 dot.color = dot.color.hex;
1600 par[2] && (dot.offset = par[2] + "%");
1603 for (i = 1, ii = dots.length - 1; i < ii; i++) {
1604 if (!dots[i].offset) {
1605 var start = toFloat(dots[i - 1].offset || 0),
1607 for (var j = i + 1; j < ii; j++) {
1608 if (dots[j].offset) {
1609 end = dots[j].offset;
1618 var d = (end - start) / (j - i + 1);
1619 for (; i < j; i++) {
1621 dots[i].offset = start + "%";
1627 tear = R._tear = function (el, paper) {
1628 el == paper.top && (paper.top = el.prev);
1629 el == paper.bottom && (paper.bottom = el.next);
1630 el.next && (el.next.prev = el.prev);
1631 el.prev && (el.prev.next = el.next);
1633 tofront = R._tofront = function (el, paper) {
1634 if (paper.top === el) {
1639 el.prev = paper.top;
1640 paper.top.next = el;
1643 toback = R._toback = function (el, paper) {
1644 if (paper.bottom === el) {
1648 el.next = paper.bottom;
1650 paper.bottom.prev = el;
1653 insertafter = R._insertafter = function (el, el2, paper) {
1655 el2 == paper.top && (paper.top = el);
1656 el2.next && (el2.next.prev = el);
1661 insertbefore = R._insertbefore = function (el, el2, paper) {
1663 el2 == paper.bottom && (paper.bottom = el);
1664 el2.prev && (el2.prev.next = el);
1669 removed = function (methodname) {
1670 return function () {
1671 throw new Error("Rapha\xebl: you are calling to method \u201c" + methodname + "\u201d of removed object");
1674 extractTransform = R._extractTransform = function (el, tstr) {
1676 return el._.transform;
1678 tstr = Str(tstr).replace(/\.{3}|\u2026/g, el._.transform || E);
1679 var tdata = R.parseTransformString(tstr),
1687 _.transform = tdata || [];
1689 for (var i = 0, ii = tdata.length; i < ii; i++) {
1693 t[0] = Str(t[0]).toLowerCase();
1694 if (t[0] == "t" && tlen == 3) {
1695 m.translate(t[1], t[2]);
1696 } else if (t[0] == "r") {
1698 bb = bb || el.getBBox(1);
1699 m.rotate(t[1], bb.x + bb.width / 2, bb.y + bb.height / 2);
1701 } else if (tlen == 4) {
1702 m.rotate(t[1], t[2], t[3]);
1705 } else if (t[0] == "s") {
1706 if (tlen == 2 || tlen == 3) {
1707 bb = bb || el.getBBox(1);
1708 m.scale(t[1], t[tlen - 1], bb.x + bb.width / 2, bb.y + bb.height / 2);
1711 } else if (tlen == 5) {
1712 m.scale(t[1], t[2], t[3], t[4]);
1716 } else if (t[0] == "m" && tlen == 7) {
1717 m.add(t[1], t[2], t[3], t[4], t[5], t[6]);
1732 if (sx == 1 && sy == 1 && !deg && _.bbox) {
1739 getEmpty = function (item) {
1741 case "t": return ["t", 0, 0];
1742 case "m": return ["m", 1, 0, 0, 1, 0, 0];
1743 case "r": if (item.length == 4) {
1744 return ["r", 0, item[2], item[3]];
1748 case "s": if (item.length == 5) {
1749 return ["s", 1, 1, item[3], item[4]];
1750 } else if (item.length == 3) {
1757 equaliseTransform = R._equaliseTransform = function (t1, t2) {
1758 t2 = Str(t2).replace(/\.{3}|\u2026/g, t1);
1759 t1 = R.parseTransformString(t1) || [];
1760 t2 = R.parseTransformString(t2) || [];
1761 var maxlength = mmax(t1.length, t2.length),
1766 for (; i < maxlength; i++) {
1767 tt1 = t1[i] || getEmpty(t2[i]);
1768 tt2 = t2[i] || getEmpty(tt1);
1769 if ((tt1[0] != tt2[0]) ||
1770 (tt1[0] == "r" && (tt1[2] != tt2[2] || tt1[3] != tt2[3])) ||
1771 (tt1[0] == "s" && (tt1[3] != tt2[3] || tt1[4] != tt2[4]))
1777 for (j = 0, jj = mmax(tt1.length, tt2.length); j < jj; j++) {
1778 j in tt1 && (from[i][j] = tt1[j]);
1779 j in tt2 && (to[i][j] = tt2[j]);
1787 R._getContainer = function (x, y, w, h) {
1789 container = h == null && !R.is(x, "object") ? g.doc.getElementById(x) : x;
1790 if (container == null) {
1793 if (container.tagName) {
1796 container: container,
1797 width: container.style.pixelWidth || container.offsetWidth,
1798 height: container.style.pixelHeight || container.offsetHeight
1802 container: container,
1817 * Raphael.pathToRelative
1822 * Converts path to relative form
1824 - pathString (string|array) path string or array of segments
1825 = (array) array of segments.
1827 R.pathToRelative = pathToRelative;
1830 * Raphael.path2curve
1835 * Converts path to a new path where all segments are cubic bezier curves.
1837 - pathString (string|array) path string or array of segments
1838 = (array) array of segments.
1840 R.path2curve = path2curve;
1847 * Returns matrix based on given parameters.
1857 R.matrix = function (a, b, c, d, e, f) {
1858 return new Matrix(a, b, c, d, e, f);
1860 function Matrix(a, b, c, d, e, f) {
1877 (function (matrixproto) {
1882 * Adds given matrix to existing one.
1891 - matrix (object) @Matrix
1893 matrixproto.add = function (a, b, c, d, e, f) {
1894 var out = [[], [], []],
1895 m = [[this.a, this.c, this.e], [this.b, this.d, this.f], [0, 0, 1]],
1896 matrix = [[a, c, e], [b, d, f], [0, 0, 1]],
1899 if (a && a instanceof Matrix) {
1900 matrix = [[a.a, a.c, a.e], [a.b, a.d, a.f], [0, 0, 1]];
1903 for (x = 0; x < 3; x++) {
1904 for (y = 0; y < 3; y++) {
1906 for (z = 0; z < 3; z++) {
1907 res += m[x][z] * matrix[z][y];
1923 * Returns inverted version of the matrix
1926 matrixproto.invert = function () {
1928 x = me.a * me.d - me.b * me.c;
1929 return new Matrix(me.d / x, -me.b / x, -me.c / x, me.a / x, (me.c * me.f - me.d * me.e) / x, (me.b * me.e - me.a * me.f) / x);
1935 * Returns copy of the matrix
1938 matrixproto.clone = function () {
1939 return new Matrix(this.a, this.b, this.c, this.d, this.e, this.f);
1945 * Translate the matrix
1950 matrixproto.translate = function (x, y) {
1951 this.add(1, 0, 0, 1, x, y);
1960 - y (number) #optional
1961 - cx (number) #optional
1962 - cy (number) #optional
1964 matrixproto.scale = function (x, y, cx, cy) {
1965 y == null && (y = x);
1966 cx || cy && this.add(1, 0, 0, 1, cx, cy);
1967 this.add(x, 0, 0, y, 0, 0);
1968 cx || cy && this.add(1, 0, 0, 1, -cx, -cy);
1974 * Rotates the matrix
1980 matrixproto.rotate = function (a, x, y) {
1984 var cos = +math.cos(a).toFixed(9),
1985 sin = +math.sin(a).toFixed(9);
1986 this.add(cos, sin, -sin, cos, x, y);
1987 this.add(1, 0, 0, 1, -x, -y);
1993 * Return x coordinate for given point after transformation described by the matrix. See also @Matrix.y
1999 matrixproto.x = function (x, y) {
2000 return x * this.a + y * this.c + this.e;
2006 * Return y coordinate for given point after transformation described by the matrix. See also @Matrix.x
2012 matrixproto.y = function (x, y) {
2013 return x * this.b + y * this.d + this.f;
2015 matrixproto.get = function (i) {
2016 return +this[Str.fromCharCode(97 + i)].toFixed(4);
2018 matrixproto.toString = function () {
2020 "matrix(" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)].join() + ")" :
2021 [this.get(0), this.get(2), this.get(1), this.get(3), 0, 0].join();
2023 matrixproto.toFilter = function () {
2024 return "progid:DXImageTransform.Microsoft.Matrix(M11=" + this.get(0) +
2025 ", M12=" + this.get(2) + ", M21=" + this.get(1) + ", M22=" + this.get(3) +
2026 ", Dx=" + this.get(4) + ", Dy=" + this.get(5) + ", sizingmethod='auto expand')";
2028 matrixproto.offset = function () {
2029 return [this.e.toFixed(4), this.f.toFixed(4)];
2032 return a[0] * a[0] + a[1] * a[1];
2034 function normalize(a) {
2035 var mag = math.sqrt(norm(a));
2036 a[0] && (a[0] /= mag);
2037 a[1] && (a[1] /= mag);
2043 * Splits matrix into primitive transformations
2044 = (object) in format:
2045 o dx (number) translation by x
2046 o dy (number) translation by y
2047 o scalex (number) scale by x
2048 o scaley (number) scale by y
2049 o shear (number) shear
2050 o rotate (number) rotation in deg
2051 o isSimple (boolean) could it be represented via simple transformations
2053 matrixproto.split = function () {
2060 var row = [[this.a, this.c], [this.b, this.d]];
2061 out.scalex = math.sqrt(norm(row[0]));
2064 out.shear = row[0][0] * row[1][0] + row[0][1] * row[1][1];
2065 row[1] = [row[1][0] - row[0][0] * out.shear, row[1][1] - row[0][1] * out.shear];
2067 out.scaley = math.sqrt(norm(row[1]));
2069 out.shear /= out.scaley;
2072 var sin = -row[0][1],
2075 out.rotate = R.deg(math.acos(cos));
2077 out.rotate = 360 - out.rotate;
2080 out.rotate = R.deg(math.asin(sin));
2083 out.isSimple = !+out.shear.toFixed(9) && (out.scalex.toFixed(9) == out.scaley.toFixed(9) || !out.rotate);
2084 out.isSuperSimple = !+out.shear.toFixed(9) && out.scalex.toFixed(9) == out.scaley.toFixed(9) && !out.rotate;
2085 out.noRotation = !+out.shear.toFixed(9) && !out.rotate;
2089 * Matrix.toTransformString
2092 * Return transform string that represents given matrix
2093 = (string) transform string
2095 matrixproto.toTransformString = function () {
2096 var s = this.split();
2098 return "t" + [s.dx, s.dy] + "s" + [s.scalex, s.scaley, 0, 0] + "r" + [s.rotate, 0, 0];
2100 return "m" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)];
2103 })(Matrix.prototype);
2105 // WebKit rendering bug workaround method
2106 var version = navigator.userAgent.match(/Version\/(.*?)\s/) || navigator.userAgent.match(/Chrome\/(\d+)/);
2107 if ((navigator.vendor == "Apple Computer, Inc.") && (version && version[1] < 4 || navigator.platform.slice(0, 2) == "iP") ||
2108 (navigator.vendor == "Google Inc." && version && version[1] < 8)) {
2113 * There is an inconvenient rendering bug in Safari (WebKit):
2114 * sometimes the rendering should be forced.
2115 * This method should help with dealing with this bug.
2117 paperproto.safari = function () {
2118 var rect = this.rect(-99, -99, this.width + 99, this.height + 99).attr({stroke: "none"});
2119 setTimeout(function () {rect.remove();});
2122 paperproto.safari = fun;
2126 var preventDefault = function () {
2127 this.returnValue = false;
2129 preventTouch = function () {
2130 return this.originalEvent.preventDefault();
2132 stopPropagation = function () {
2133 this.cancelBubble = true;
2135 stopTouch = function () {
2136 return this.originalEvent.stopPropagation();
2138 addEvent = (function () {
2139 if (g.doc.addEventListener) {
2140 return function (obj, type, fn, element) {
2141 var realName = supportsTouch && touchMap[type] ? touchMap[type] : type,
2143 var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
2144 scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft,
2145 x = e.clientX + scrollX,
2146 y = e.clientY + scrollY;
2147 if (supportsTouch && touchMap[has](type)) {
2148 for (var i = 0, ii = e.targetTouches && e.targetTouches.length; i < ii; i++) {
2149 if (e.targetTouches[i].target == obj) {
2151 e = e.targetTouches[i];
2152 e.originalEvent = olde;
2153 e.preventDefault = preventTouch;
2154 e.stopPropagation = stopTouch;
2159 return fn.call(element, e, x, y);
2161 obj.addEventListener(realName, f, false);
2162 return function () {
2163 obj.removeEventListener(realName, f, false);
2167 } else if (g.doc.attachEvent) {
2168 return function (obj, type, fn, element) {
2169 var f = function (e) {
2170 e = e || g.win.event;
2171 var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
2172 scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft,
2173 x = e.clientX + scrollX,
2174 y = e.clientY + scrollY;
2175 e.preventDefault = e.preventDefault || preventDefault;
2176 e.stopPropagation = e.stopPropagation || stopPropagation;
2177 return fn.call(element, e, x, y);
2179 obj.attachEvent("on" + type, f);
2180 var detacher = function () {
2181 obj.detachEvent("on" + type, f);
2189 dragMove = function (e) {
2192 scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
2193 scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft,
2198 if (supportsTouch) {
2199 var i = e.touches.length,
2202 touch = e.touches[i];
2203 if (touch.identifier == dragi.el._drag.id) {
2206 (e.originalEvent ? e.originalEvent : e).preventDefault();
2213 var node = dragi.el.node,
2215 next = node.nextSibling,
2216 parent = node.parentNode,
2217 display = node.style.display;
2218 g.win.opera && parent.removeChild(node);
2219 node.style.display = "none";
2220 o = dragi.el.paper.getElementByPoint(x, y);
2221 node.style.display = display;
2222 g.win.opera && (next ? parent.insertBefore(node, next) : parent.appendChild(node));
2223 o && eve("drag.over." + dragi.el.id, dragi.el, o);
2226 eve("drag.move." + dragi.el.id, dragi.move_scope || dragi.el, x - dragi.el._drag.x, y - dragi.el._drag.y, x, y, e);
2229 dragUp = function (e) {
2230 R.unmousemove(dragMove).unmouseup(dragUp);
2231 var i = drag.length,
2235 dragi.el._drag = {};
2236 eve("drag.end." + dragi.el.id, dragi.end_scope || dragi.start_scope || dragi.move_scope || dragi.el, e);
2242 [ property (object) ]
2244 * You can add your own method to elements. This is usefull when you want to hack default functionality or
2245 * want to wrap some common transformation or attributes in one method. In difference to canvas methods,
2246 * you can redefine element method at any time. Expending element methods wouldn’t affect set.
2248 | Raphael.el.red = function () {
2249 | this.attr({fill: "#f00"});
2252 | paper.circle(100, 100, 20).red();
2254 elproto = R.el = {};
2259 * Adds event handler for click for the element.
2261 - handler (function) handler for the event
2268 * Removes event handler for click for the element.
2270 - handler (function) handler for the event
2278 * Adds event handler for double click for the element.
2280 - handler (function) handler for the event
2284 * Element.undblclick
2287 * Removes event handler for double click for the element.
2289 - handler (function) handler for the event
2297 * Adds event handler for mousedown for the element.
2299 - handler (function) handler for the event
2303 * Element.unmousedown
2306 * Removes event handler for mousedown for the element.
2308 - handler (function) handler for the event
2316 * Adds event handler for mousemove for the element.
2318 - handler (function) handler for the event
2322 * Element.unmousemove
2325 * Removes event handler for mousemove for the element.
2327 - handler (function) handler for the event
2335 * Adds event handler for mouseout for the element.
2337 - handler (function) handler for the event
2341 * Element.unmouseout
2344 * Removes event handler for mouseout for the element.
2346 - handler (function) handler for the event
2354 * Adds event handler for mouseover for the element.
2356 - handler (function) handler for the event
2360 * Element.unmouseover
2363 * Removes event handler for mouseover for the element.
2365 - handler (function) handler for the event
2373 * Adds event handler for mouseup for the element.
2375 - handler (function) handler for the event
2382 * Removes event handler for mouseup for the element.
2384 - handler (function) handler for the event
2389 * Element.touchstart
2392 * Adds event handler for touchstart for the element.
2394 - handler (function) handler for the event
2398 * Element.untouchstart
2401 * Removes event handler for touchstart for the element.
2403 - handler (function) handler for the event
2411 * Adds event handler for touchmove for the element.
2413 - handler (function) handler for the event
2417 * Element.untouchmove
2420 * Removes event handler for touchmove for the element.
2422 - handler (function) handler for the event
2430 * Adds event handler for touchend for the element.
2432 - handler (function) handler for the event
2436 * Element.untouchend
2439 * Removes event handler for touchend for the element.
2441 - handler (function) handler for the event
2446 * Element.touchcancel
2449 * Adds event handler for touchcancel for the element.
2451 - handler (function) handler for the event
2455 * Element.untouchcancel
2458 * Removes event handler for touchcancel for the element.
2460 - handler (function) handler for the event
2463 for (var i = events.length; i--;) {
2464 (function (eventName) {
2465 R[eventName] = elproto[eventName] = function (fn, scope) {
2466 if (R.is(fn, "function")) {
2467 this.events = this.events || [];
2468 this.events.push({name: eventName, f: fn, unbind: addEvent(this.shape || this.node || g.doc, eventName, fn, scope || this)});
2472 R["un" + eventName] = elproto["un" + eventName] = function (fn) {
2473 var events = this.events,
2475 while (l--) if (events[l].name == eventName && events[l].f == fn) {
2477 events.splice(l, 1);
2478 !events.length && delete this.events;
2490 * Adds or retrieves given value asociated with given key.
2492 * See also @Element.removeData
2494 - key (string) key to store data
2495 - value (any) #optional value to store
2497 * or, if value is not specified:
2500 | for (var i = 0, i < 5, i++) {
2501 | paper.circle(10 + 15 * i, 10, 10)
2502 | .attr({fill: "#000"})
2504 | .click(function () {
2505 | alert(this.data("i"));
2509 elproto.data = function (key, value) {
2510 var data = eldata[this.id] = eldata[this.id] || {};
2511 if (arguments.length == 1) {
2512 if (R.is(key, "object")) {
2513 for (var i in key) if (key[has](i)) {
2514 this.data(i, key[i]);
2518 eve("data.get." + this.id, this, data[key], key);
2522 eve("data.set." + this.id, this, value, key);
2526 * Element.removeData
2529 * Removes value associated with an element by given key.
2530 * If key is not provided, removes all the data of the element.
2532 - key (string) #optional key
2535 elproto.removeData = function (key) {
2537 eldata[this.id] = {};
2539 eldata[this.id] && delete eldata[this.id][key];
2547 * Adds event handlers for hover for the element.
2549 - f_in (function) handler for hover in
2550 - f_out (function) handler for hover out
2551 - icontext (object) #optional context for hover in handler
2552 - ocontext (object) #optional context for hover out handler
2555 elproto.hover = function (f_in, f_out, scope_in, scope_out) {
2556 return this.mouseover(f_in, scope_in).mouseout(f_out, scope_out || scope_in);
2562 * Removes event handlers for hover for the element.
2564 - f_in (function) handler for hover in
2565 - f_out (function) handler for hover out
2568 elproto.unhover = function (f_in, f_out) {
2569 return this.unmouseover(f_in).unmouseout(f_out);
2575 * Adds event handlers for drag of the element.
2577 - onmove (function) handler for moving
2578 - onstart (function) handler for drag start
2579 - onend (function) handler for drag end
2580 - mcontext (object) #optional context for moving handler
2581 - scontext (object) #optional context for drag start handler
2582 - econtext (object) #optional context for drag end handler
2583 * Additionaly following `drag` events will be triggered: `drag.start.<id>` on start,
2584 * `drag.end.<id>` on end and `drag.move.<id>` on every move. When element will be dragged over another element
2585 * `drag.over.<id>` will be fired as well.
2587 * Start event and start handler will be called in specified context or in context of the element with following parameters:
2588 o x (number) x position of the mouse
2589 o y (number) y position of the mouse
2590 o event (object) DOM event object
2591 * Move event and move handler will be called in specified context or in context of the element with following parameters:
2592 o dx (number) shift by x from the start point
2593 o dy (number) shift by y from the start point
2594 o x (number) x position of the mouse
2595 o y (number) y position of the mouse
2596 o event (object) DOM event object
2597 * End event and end handler will be called in specified context or in context of the element with following parameters:
2598 o event (object) DOM event object
2601 elproto.drag = function (onmove, onstart, onend, move_scope, start_scope, end_scope) {
2603 (e.originalEvent || e).preventDefault();
2604 var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
2605 scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft;
2606 this._drag.x = e.clientX + scrollX;
2607 this._drag.y = e.clientY + scrollY;
2608 this._drag.id = e.identifier;
2609 !drag.length && R.mousemove(dragMove).mouseup(dragUp);
2610 drag.push({el: this, move_scope: move_scope, start_scope: start_scope, end_scope: end_scope});
2611 onstart && eve.on("drag.start." + this.id, onstart);
2612 onmove && eve.on("drag.move." + this.id, onmove);
2613 onend && eve.on("drag.end." + this.id, onend);
2614 eve("drag.start." + this.id, start_scope || move_scope || this, e.clientX + scrollX, e.clientY + scrollY, e);
2617 this.mousedown(start);
2621 * Element.onDragOver
2624 * Shortcut for assigning event handler for `drag.over.<id>` event, where id is id of the element (see @Element.id).
2626 - f (function) handler for event
2628 elproto.onDragOver = function (f) {
2629 f ? eve.on("drag.over." + this.id, f) : eve.unbind("drag.over." + this.id);
2635 * Removes all drag event handlers from given element.
2637 elproto.undrag = function () {
2638 var i = drag.length;
2639 while (i--) if (drag[i].el == this) {
2640 R.unmousedown(drag[i].start);
2641 drag.splice(i++, 1);
2642 eve.unbind("drag.*." + this.id);
2644 !drag.length && R.unmousemove(dragMove).unmouseup(dragUp);
2654 - x (number) x coordinate of the centre
2655 - y (number) y coordinate of the centre
2657 = (object) Raphaël element object with type “circle”
2660 | var c = paper.circle(50, 50, 40);
2662 paperproto.circle = function (x, y, r) {
2663 var out = R._engine.circle(this, x || 0, y || 0, r || 0);
2664 this.__set__ && this.__set__.push(out);
2671 * Draws a rectangle.
2675 - x (number) x coordinate of the top left corner
2676 - y (number) y coordinate of the top left corner
2677 - width (number) width
2678 - height (number) height
2679 - r (number) #optional radius for rounded corners, default is 0
2680 = (object) Raphaël element object with type “rect”
2683 | // regular rectangle
2684 | var c = paper.rect(10, 10, 50, 50);
2685 | // rectangle with rounded corners
2686 | var c = paper.rect(40, 40, 50, 50, 10);
2688 paperproto.rect = function (x, y, w, h, r) {
2689 var out = R._engine.rect(this, x || 0, y || 0, w || 0, h || 0, r || 0);
2690 this.__set__ && this.__set__.push(out);
2701 - x (number) x coordinate of the centre
2702 - y (number) y coordinate of the centre
2703 - rx (number) horizontal radius
2704 - ry (number) vertical radius
2705 = (object) Raphaël element object with type “ellipse”
2708 | var c = paper.ellipse(50, 50, 40, 20);
2710 paperproto.ellipse = function (x, y, rx, ry) {
2711 var out = R._engine.ellipse(this, x || 0, y || 0, rx || 0, ry || 0);
2712 this.__set__ && this.__set__.push(out);
2719 * Creates a path element by given path data string.
2723 - pathString (string) path data in SVG path string format.
2724 = (object) Raphaël element object with type “path”
2725 # Details of a path's data attribute's format are described in the <a href="http://www.w3.org/TR/SVG/paths.html#PathData">SVG specification</a>.
2728 | var c = paper.path("M10 10L90 90");
2729 | // draw a diagonal line:
2730 | // move to 10,10, line to 90,90
2732 paperproto.path = function (pathString) {
2733 pathString && !R.is(pathString, string) && !R.is(pathString[0], array) && (pathString += E);
2734 var out = R._engine.path(R.format[apply](R, arguments), this);
2735 this.__set__ && this.__set__.push(out);
2742 * Embeds an image into the surface.
2746 - src (string) URI of the source image
2747 - x (number) x coordinate position
2748 - y (number) y coordinate position
2749 - width (number) width of the image
2750 - height (number) height of the image
2751 = (object) Raphaël element object with type “image”
2754 | var c = paper.image("apple.png", 10, 10, 80, 80);
2756 paperproto.image = function (src, x, y, w, h) {
2757 var out = R._engine.image(this, src || "about:blank", x || 0, y || 0, w || 0, h || 0);
2758 this.__set__ && this.__set__.push(out);
2765 * Draws a text string. If you need line breaks, put “\n” in the string.
2769 - x (number) x coordinate position
2770 - y (number) y coordinate position
2771 - text (string) The text string to draw
2772 = (object) Raphaël element object with type “text”
2775 | var t = paper.text(50, 50, "Raphaël\nkicks\nbutt!");
2777 paperproto.text = function (x, y, text) {
2778 var out = R._engine.text(this, x || 0, y || 0, Str(text));
2779 this.__set__ && this.__set__.push(out);
2786 * Creates array-like object to keep and operate several elements at once.
2787 * Warning: it doesn’t create any elements for itself in the page, it just groups existing elements.
2788 * Sets act as pseudo elements — all methods available to an element can be used on a set.
2789 = (object) array-like object that represents set of elements
2792 | var st = paper.set();
2794 | paper.circle(10, 10, 5),
2795 | paper.circle(30, 10, 5)
2797 | st.attr({fill: "red"}); // changes the fill of both circles
2799 paperproto.set = function (itemsArray) {
2800 !R.is(itemsArray, "array") && (itemsArray = Array.prototype.splice.call(arguments, 0, arguments.length));
2801 var out = new Set(itemsArray);
2802 this.__set__ && this.__set__.push(out);
2809 * Creates @Paper.set. All elements that will be created after calling this method and before calling
2810 * @Paper.setFinish will be added to the set.
2814 | paper.circle(10, 10, 5),
2815 | paper.circle(30, 10, 5)
2816 | var st = paper.setFinish();
2817 | st.attr({fill: "red"}); // changes the fill of both circles
2819 paperproto.setStart = function (set) {
2820 this.__set__ = set || this.set();
2826 * See @Paper.setStart. This method finishes catching and returns resulting set.
2830 paperproto.setFinish = function (set) {
2831 var out = this.__set__;
2832 delete this.__set__;
2839 * If you need to change dimensions of the canvas call this method
2843 - width (number) new width of the canvas
2844 - height (number) new height of the canvas
2846 | var st = paper.set();
2848 | paper.circle(10, 10, 5),
2849 | paper.circle(30, 10, 5)
2851 | st.attr({fill: "red"});
2853 paperproto.setSize = function (width, height) {
2854 return R._engine.setSize.call(this, width, height);
2860 * Sets the view box of the paper. Practically it gives you ability to zoom and pan whole paper surface by
2861 * specifying new boundaries.
2865 - x (number) new x position, default is `0`
2866 - y (number) new y position, default is `0`
2867 - w (number) new width of the canvas
2868 - h (number) new height of the canvas
2869 - fit (boolean) `true` if you want graphics to fit into new boundary box
2871 paperproto.setViewBox = function (x, y, w, h, fit) {
2872 return R._engine.setViewBox.call(this, x, y, w, h, fit);
2878 * Points to the topmost element on the paper
2884 * Points to the bottom element on the paper
2886 paperproto.top = paperproto.bottom = null;
2891 * Points to the @Raphael object/function
2893 paperproto.raphael = R;
2894 var getOffset = function (elem) {
2895 var box = elem.getBoundingClientRect(),
2896 doc = elem.ownerDocument,
2898 docElem = doc.documentElement,
2899 clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0,
2900 top = box.top + (g.win.pageYOffset || docElem.scrollTop || body.scrollTop ) - clientTop,
2901 left = box.left + (g.win.pageXOffset || docElem.scrollLeft || body.scrollLeft) - clientLeft;
2908 * Paper.getElementByPoint
2911 * Returns you topmost element under given point.
2913 = (object) Raphaël element object
2916 - x (number) x coordinate from the top left corner of the window
2917 - y (number) y coordinate from the top left corner of the window
2919 | paper.getElementByPoint(mouseX, mouseY).attr({stroke: "#f00"});
2921 paperproto.getElementByPoint = function (x, y) {
2924 target = g.doc.elementFromPoint(x, y);
2925 if (g.win.opera && target.tagName == "svg") {
2926 var so = getOffset(svg),
2927 sr = svg.createSVGRect();
2930 sr.width = sr.height = 1;
2931 var hits = svg.getIntersectionList(sr, null);
2933 target = hits[hits.length - 1];
2939 while (target.parentNode && target != svg.parentNode && !target.raphael) {
2940 target = target.parentNode;
2942 target == paper.canvas.parentNode && (target = svg);
2943 target = target && target.raphael ? paper.getById(target.raphaelid) : null;
2950 * Returns you element by its internal ID.
2955 = (object) Raphaël element object
2957 paperproto.getById = function (id) {
2958 var bot = this.bottom;
2971 * Executes given function for each element on the paper
2973 * If callback function returns `false` it will stop loop running.
2977 - callback (function) function to run
2978 - thisArg (object) context object for the callback
2979 = (object) Paper object
2981 paperproto.forEach = function (callback, thisArg) {
2982 var bot = this.bottom;
2984 if (callback.call(thisArg, bot) === false) {
2992 return this.x + S + this.y;
2994 function x_y_w_h() {
2995 return this.x + S + this.y + S + this.width + " \xd7 " + this.height;
3001 * Return bounding box for a given element
3005 - isWithoutTransform (boolean) flag, `true` if you want to have bounding box before transformations. Default is `false`.
3006 = (object) Bounding box object:
3008 o x: (number) top left corner x
3009 o y: (number) top left corner y
3010 o width: (number) width
3011 o height: (number) height
3014 elproto.getBBox = function (isWithoutTransform) {
3019 if (isWithoutTransform) {
3020 if (_.dirty || !_.bboxwt) {
3021 this.realPath = getPath[this.type](this);
3022 _.bboxwt = pathDimensions(this.realPath);
3023 _.bboxwt.toString = x_y_w_h;
3028 if (_.dirty || _.dirtyT || !_.bbox) {
3029 if (_.dirty || !this.realPath) {
3031 this.realPath = getPath[this.type](this);
3033 _.bbox = pathDimensions(mapPath(this.realPath, this.matrix));
3034 _.bbox.toString = x_y_w_h;
3035 _.dirty = _.dirtyT = 0;
3043 = (object) clone of a given element
3046 elproto.clone = function () {
3050 return this.paper[this.type]().attr(this.attr());
3056 * Return set of elements that create glow-like effect around given element. See @Paper.set.
3058 * Note: Glow is not connected to the element. If you change element attributes it won’t adjust itself.
3062 - glow (object) #optional parameters object with all properties optional:
3064 o width (number) size of the glow, default is `10`
3065 o fill (boolean) will it be filled, default is `false`
3066 o opacity (number) opacity, default is `0.5`
3067 o offsetx (number) horizontal offset, default is `0`
3068 o offsety (number) vertical offset, default is `0`
3069 o color (string) glow colour, default is `black`
3071 = (object) @Paper.set of elements that represents glow
3073 elproto.glow = function (glow) {
3074 if (this.type == "text") {
3079 width: (glow.width || 10) + (+this.attr("stroke-width") || 1),
3080 fill: glow.fill || false,
3081 opacity: glow.opacity || .5,
3082 offsetx: glow.offsetx || 0,
3083 offsety: glow.offsety || 0,
3084 color: glow.color || "#000"
3089 path = this.realPath || getPath[this.type](this);
3090 path = this.matrix ? mapPath(path, this.matrix) : path;
3091 for (var i = 1; i < c + 1; i++) {
3092 out.push(r.path(path).attr({
3094 fill: s.fill ? s.color : "none",
3095 "stroke-linejoin": "round",
3096 "stroke-linecap": "round",
3097 "stroke-width": +(s.width / c * i).toFixed(3),
3098 opacity: +(s.opacity / c).toFixed(3)
3101 return out.insertBefore(this).translate(s.offsetx, s.offsety);
3103 var curveslengths = {},
3104 getPointAtSegmentLength = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length) {
3107 name = [p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y].join(),
3108 cache = curveslengths[name],
3110 !cache && (curveslengths[name] = cache = {data: []});
3111 cache.timer && clearTimeout(cache.timer);
3112 cache.timer = setTimeout(function () {delete curveslengths[name];}, 2e3);
3113 if (length != null && !cache.precision) {
3114 var total = getPointAtSegmentLength(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y);
3115 cache.precision = ~~total * 10;
3118 precision = cache.precision || precision;
3119 for (var i = 0; i < precision + 1; i++) {
3120 if (cache.data[i * precision]) {
3121 dot = cache.data[i * precision];
3123 dot = R.findDotsAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, i / precision);
3124 cache.data[i * precision] = dot;
3126 i && (len += pow(pow(old.x - dot.x, 2) + pow(old.y - dot.y, 2), .5));
3127 if (length != null && len >= length) {
3132 if (length == null) {
3136 getLengthFactory = function (istotal, subpath) {
3137 return function (path, length, onlystart) {
3138 path = path2curve(path);
3139 var x, y, p, l, sp = "", subpaths = {}, point,
3141 for (var i = 0, ii = path.length; i < ii; i++) {
3147 l = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6]);
3148 if (len + l > length) {
3149 if (subpath && !subpaths.start) {
3150 point = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6], length - len);
3151 sp += ["C" + point.start.x, point.start.y, point.m.x, point.m.y, point.x, point.y];
3152 if (onlystart) {return sp;}
3153 subpaths.start = sp;
3154 sp = ["M" + point.x, point.y + "C" + point.n.x, point.n.y, point.end.x, point.end.y, p[5], p[6]].join();
3160 if (!istotal && !subpath) {
3161 point = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6], length - len);
3162 return {x: point.x, y: point.y, alpha: point.alpha};
3169 sp += p.shift() + p;
3172 point = istotal ? len : subpath ? subpaths : R.findDotsAtSegment(x, y, p[1], p[2], p[3], p[4], p[5], p[6], 1);
3173 point.alpha && (point = {x: point.x, y: point.y, alpha: point.alpha});
3177 var getTotalLength = getLengthFactory(1),
3178 getPointAtLength = getLengthFactory(),
3179 getSubpathsAtLength = getLengthFactory(0, 1);
3181 * Raphael.getTotalLength
3184 * Returns length of the given path in pixels.
3188 - path (string) SVG path string.
3192 R.getTotalLength = getTotalLength;
3194 * Raphael.getPointAtLength
3197 * Return coordinates of the point located at the given length on the given path.
3201 - path (string) SVG path string
3204 = (object) representation of the point:
3206 o x: (number) x coordinate
3207 o y: (number) y coordinate
3208 o alpha: (number) angle of derivative
3211 R.getPointAtLength = getPointAtLength;
3213 * Raphael.getSubpath
3216 * Return subpath of a given path from given length to given length.
3220 - path (string) SVG path string
3221 - from (number) position of the start of the segment
3222 - to (number) position of the end of the segment
3224 = (string) pathstring for the segment
3226 R.getSubpath = function (path, from, to) {
3227 if (abs(this.getTotalLength(path) - to) < 1e-6) {
3228 return getSubpathsAtLength(path, from).end;
3230 var a = getSubpathsAtLength(path, to, 1);
3231 return from ? getSubpathsAtLength(a, from).end : a;
3234 * Element.getTotalLength
3237 * Returns length of the path in pixels. Only works for element of “path” type.
3240 elproto.getTotalLength = function () {
3241 if (this.type != "path") {return;}
3242 if (this.node.getTotalLength) {
3243 return this.node.getTotalLength();
3245 return getTotalLength(this.attrs.path);
3248 * Element.getPointAtLength
3251 * Return coordinates of the point located at the given length on the given path. Only works for element of “path” type.
3257 = (object) representation of the point:
3259 o x: (number) x coordinate
3260 o y: (number) y coordinate
3261 o alpha: (number) angle of derivative
3264 elproto.getPointAtLength = function (length) {
3265 if (this.type != "path") {return;}
3266 return getPointAtLength(this.attrs.path, length);
3269 * Element.getSubpath
3272 * Return subpath of a given element from given length to given length. Only works for element of “path” type.
3276 - from (number) position of the start of the segment
3277 - to (number) position of the end of the segment
3279 = (string) pathstring for the segment
3281 elproto.getSubpath = function (from, to) {
3282 if (this.type != "path") {return;}
3283 return R.getSubpath(this.attrs.path, from, to);
3286 * Raphael.easing_formulas
3289 * Object that contains easing formulas for animation. You could extend it with your own. By default it has following list of easing:
3292 # <li>“<” or “easeIn” or “ease-in”</li>
3293 # <li>“>” or “easeOut” or “ease-out”</li>
3294 # <li>“<>” or “easeInOut” or “ease-in-out”</li>
3295 # <li>“backIn” or “back-in”</li>
3296 # <li>“backOut” or “back-out”</li>
3297 # <li>“elastic”</li>
3300 # <p>See also <a href="http://raphaeljs.com/easing.html">Easing demo</a>.</p>
3302 var ef = R.easing_formulas = {
3303 linear: function (n) {
3312 "<>": function (n) {
3313 var q = .48 - n / 1.04,
3314 Q = math.sqrt(.1734 + q * q),
3316 X = pow(abs(x), 1 / 3) * (x < 0 ? -1 : 1),
3318 Y = pow(abs(y), 1 / 3) * (y < 0 ? -1 : 1),
3320 return (1 - t) * 3 * t * t + t * t * t;
3322 backIn: function (n) {
3324 return n * n * ((s + 1) * n - s);
3326 backOut: function (n) {
3329 return n * n * ((s + 1) * n + s) + 1;
3331 elastic: function (n) {
3335 return pow(2, -10 * n) * math.sin((n - .075) * (2 * PI) / .3) + 1;
3337 bounce: function (n) {
3346 l = s * n * n + .75;
3348 if (n < (2.5 / p)) {
3350 l = s * n * n + .9375;
3353 l = s * n * n + .984375;
3360 ef.easeIn = ef["ease-in"] = ef["<"];
3361 ef.easeOut = ef["ease-out"] = ef[">"];
3362 ef.easeInOut = ef["ease-in-out"] = ef["<>"];
3363 ef["back-in"] = ef.backIn;
3364 ef["back-out"] = ef.backOut;
3366 var animationElements = [],
3367 requestAnimFrame = window.requestAnimationFrame ||
3368 window.webkitRequestAnimationFrame ||
3369 window.mozRequestAnimationFrame ||
3370 window.oRequestAnimationFrame ||
3371 window.msRequestAnimationFrame ||
3372 function (callback) {
3373 setTimeout(callback, 16);
3375 animation = function () {
3376 var Now = +new Date,
3378 for (; l < animationElements.length; l++) {
3379 var e = animationElements[l];
3380 if (e.el.removed || e.paused) {
3383 var time = Now - e.start,
3394 time = (e.initstatus * e.anim.top - e.prev) / (e.percent - e.prev) * ms;
3395 e.status = e.initstatus;
3396 delete e.initstatus;
3397 e.stop && animationElements.splice(l--, 1);
3399 e.status = (e.prev + (e.percent - e.prev) * (time / ms)) / e.anim.top;
3405 var pos = easing(time / ms);
3406 for (var attr in from) if (from[has](attr)) {
3407 switch (availableAnimAttrs[attr]) {
3409 now = +from[attr] + pos * ms * diff[attr];
3413 upto255(round(from[attr].r + pos * ms * diff[attr].r)),
3414 upto255(round(from[attr].g + pos * ms * diff[attr].g)),
3415 upto255(round(from[attr].b + pos * ms * diff[attr].b))
3420 for (var i = 0, ii = from[attr].length; i < ii; i++) {
3421 now[i] = [from[attr][i][0]];
3422 for (var j = 1, jj = from[attr][i].length; j < jj; j++) {
3423 now[i][j] = +from[attr][i][j] + pos * ms * diff[attr][i][j];
3425 now[i] = now[i].join(S);
3430 if (diff[attr].real) {
3432 for (i = 0, ii = from[attr].length; i < ii; i++) {
3433 now[i] = [from[attr][i][0]];
3434 for (j = 1, jj = from[attr][i].length; j < jj; j++) {
3435 now[i][j] = from[attr][i][j] + pos * ms * diff[attr][i][j];
3439 var get = function (i) {
3440 return +from[attr][i] + pos * ms * diff[attr][i];
3442 // now = [["r", get(2), 0, 0], ["t", get(3), get(4)], ["s", get(0), get(1), 0, 0]];
3443 now = [["m", get(0), get(1), get(2), get(3), get(4), get(5)]];
3447 if (attr == "clip-rect") {
3451 now[i] = +from[attr][i] + pos * ms * diff[attr][i];
3456 var from2 = [].concat(from[attr]);
3458 i = that.paper.customAttributes[attr].length;
3460 now[i] = +from2[i] + pos * ms * diff[attr][i];
3467 (function (id, that, anim) {
3468 setTimeout(function () {
3469 eve("anim.frame." + id, that, anim);
3471 })(that.id, that, e.anim);
3473 (function(f, el, a) {
3474 setTimeout(function() {
3475 eve("anim.frame." + el.id, el, a);
3476 eve("anim.finish." + el.id, el, a);
3477 R.is(f, "function") && f.call(el);
3479 })(e.callback, that, e.anim);
3481 animationElements.splice(l--, 1);
3482 if (e.repeat > 1 && !e.next) {
3483 runAnimation(e.anim, e.el, e.anim.percents[0], null, e.totalOrigin, e.repeat - 1);
3485 if (e.next && !e.stop) {
3486 runAnimation(e.anim, e.el, e.next, null, e.totalOrigin, e.repeat);
3490 R.svg && that && that.paper && that.paper.safari();
3491 animationElements.length && requestAnimFrame(animation);
3493 upto255 = function (color) {
3494 return color > 255 ? 255 : color < 0 ? 0 : color;
3497 * Element.animateWith
3500 * Acts similar to @Element.animate, but ensure that given animation runs in sync with another given element.
3504 - params (object) final attributes for the element, see also @Element.attr
3505 - ms (number) number of milliseconds for animation to run
3506 - easing (string) #optional easing type. Accept on of @Raphael.easing_formulas or CSS format: `cubic‐bezier(XX, XX, XX, XX)`
3507 - callback (function) #optional callback function. Will be called at the end of animation.
3509 - animation (object) animation object, see @Raphael.animation
3511 = (object) original element
3513 elproto.animateWith = function (element, params, ms, easing, callback) {
3514 this.animate(params, ms, easing, callback);
3516 for (var i = 0, ii = animationElements.length; i < ii; i++) {
3517 el = animationElements[i];
3518 if (el.el.id == element.id) {
3519 start = el.timestamp;
3520 } else if (el.el.id == this.id) {
3524 return this.animate(params, ms, easing, callback);
3526 function CubicBezierAtTime(t, p1x, p1y, p2x, p2y, duration) {
3528 bx = 3 * (p2x - p1x) - cx,
3531 by = 3 * (p2y - p1y) - cy,
3533 function sampleCurveX(t) {
3534 return ((ax * t + bx) * t + cx) * t;
3536 function solve(x, epsilon) {
3537 var t = solveCurveX(x, epsilon);
3538 return ((ay * t + by) * t + cy) * t;
3540 function solveCurveX(x, epsilon) {
3541 var t0, t1, t2, x2, d2, i;
3542 for(t2 = x, i = 0; i < 8; i++) {
3543 x2 = sampleCurveX(t2) - x;
3544 if (abs(x2) < epsilon) {
3547 d2 = (3 * ax * t2 + 2 * bx) * t2 + cx;
3548 if (abs(d2) < 1e-6) {
3563 x2 = sampleCurveX(t2);
3564 if (abs(x2 - x) < epsilon) {
3572 t2 = (t1 - t0) / 2 + t0;
3576 return solve(t, 1 / (200 * duration));
3578 elproto.onAnimation = function (f) {
3579 f ? eve.on("anim.frame." + this.id, f) : eve.unbind("anim.frame." + this.id);
3582 function Animation(anim, ms) {
3588 for (var attr in this.anim) if (this.anim[has](attr)) {
3589 percents.push(+attr);
3591 percents.sort(sortByNumber);
3593 this.top = percents[percents.length - 1];
3594 this.percents = percents;
3600 * Creates a copy of existing animation object with given delay.
3604 - delay (number) number of ms to pass between animation start and actual animation
3606 = (object) new altered Animation object
3608 Animation.prototype.delay = function (delay) {
3609 var a = new Animation(this.anim, this.ms);
3610 a.times = this.times;
3611 a.del = +delay || 0;
3618 * Creates a copy of existing animation object with given repetition.
3622 - repeat (number) number iterations of animation. For infinite animation pass `Infinity`
3624 = (object) new altered Animation object
3626 Animation.prototype.repeat = function (times) {
3627 var a = new Animation(this.anim, this.ms);
3629 a.times = math.floor(mmax(times, 0)) || 1;
3632 function runAnimation(anim, element, percent, status, totalOrigin, times) {
3633 percent = toFloat(percent);
3646 for (i = 0, ii = animationElements.length; i < ii; i++) {
3647 var e = animationElements[i];
3648 if (e.el.id == element.id && e.anim == anim) {
3649 if (e.percent != percent) {
3650 animationElements.splice(i, 1);
3655 element.attr(e.totalOrigin);
3660 status = +to; // NaN
3662 for (var i = 0, ii = anim.percents.length; i < ii; i++) {
3663 if (anim.percents[i] == percent || anim.percents[i] > status * anim.top) {
3664 percent = anim.percents[i];
3665 prev = anim.percents[i - 1] || 0;
3666 ms = ms / anim.top * (percent - prev);
3667 next = anim.percents[i + 1];
3668 params = anim.anim[percent];
3670 } else if (status) {
3671 element.attr(anim.anim[anim.percents[i]]);
3678 for (attr in params) if (params[has](attr)) {
3679 if (availableAnimAttrs[has](attr) || element.paper.customAttributes[has](attr)) {
3680 from[attr] = element.attr(attr);
3681 (from[attr] == null) && (from[attr] = availableAttrs[attr]);
3682 to[attr] = params[attr];
3683 switch (availableAnimAttrs[attr]) {
3685 diff[attr] = (to[attr] - from[attr]) / ms;
3688 from[attr] = R.getRGB(from[attr]);
3689 var toColour = R.getRGB(to[attr]);
3691 r: (toColour.r - from[attr].r) / ms,
3692 g: (toColour.g - from[attr].g) / ms,
3693 b: (toColour.b - from[attr].b) / ms
3697 var pathes = path2curve(from[attr], to[attr]),
3699 from[attr] = pathes[0];
3701 for (i = 0, ii = from[attr].length; i < ii; i++) {
3702 diff[attr][i] = [0];
3703 for (var j = 1, jj = from[attr][i].length; j < jj; j++) {
3704 diff[attr][i][j] = (toPath[i][j] - from[attr][i][j]) / ms;
3710 eq = equaliseTransform(_[attr], to[attr]);
3712 from[attr] = eq.from;
3715 diff[attr].real = true;
3716 for (i = 0, ii = from[attr].length; i < ii; i++) {
3717 diff[attr][i] = [from[attr][i][0]];
3718 for (j = 1, jj = from[attr][i].length; j < jj; j++) {
3719 diff[attr][i][j] = (to[attr][i][j] - from[attr][i][j]) / ms;
3723 var m = (element.matrix || new Matrix),
3725 _: {transform: _.transform},
3726 getBBox: function () {
3727 return element.getBBox(1);
3738 extractTransform(to2, to[attr]);
3739 to[attr] = to2._.transform;
3741 (to2.matrix.a - m.a) / ms,
3742 (to2.matrix.b - m.b) / ms,
3743 (to2.matrix.c - m.c) / ms,
3744 (to2.matrix.d - m.d) / ms,
3745 (to2.matrix.e - m.e) / ms,
3746 (to2.matrix.e - m.f) / ms
3748 // from[attr] = [_.sx, _.sy, _.deg, _.dx, _.dy];
3749 // var to2 = {_:{}, getBBox: function () { return element.getBBox(); }};
3750 // extractTransform(to2, to[attr]);
3752 // (to2._.sx - _.sx) / ms,
3753 // (to2._.sy - _.sy) / ms,
3754 // (to2._.deg - _.deg) / ms,
3755 // (to2._.dx - _.dx) / ms,
3756 // (to2._.dy - _.dy) / ms
3761 var values = Str(params[attr]).split(separator),
3762 from2 = Str(from[attr]).split(separator);
3763 if (attr == "clip-rect") {
3768 diff[attr][i] = (values[i] - from[attr][i]) / ms;
3774 values = [].concat(params[attr]);
3775 from2 = [].concat(from[attr]);
3777 i = element.paper.customAttributes[attr].length;
3779 diff[attr][i] = ((values[i] || 0) - (from2[i] || 0)) / ms;
3785 var easing = params.easing,
3786 easyeasy = R.easing_formulas[easing];
3788 easyeasy = Str(easing).match(bezierrg);
3789 if (easyeasy && easyeasy.length == 5) {
3790 var curve = easyeasy;
3791 easyeasy = function (t) {
3792 return CubicBezierAtTime(t, +curve[1], +curve[2], +curve[3], +curve[4], ms);
3798 timestamp = params.start || anim.start || +new Date;
3802 timestamp: timestamp,
3803 start: timestamp + (anim.del || 0),
3805 initstatus: status || 0,
3813 callback: params.callback,
3816 repeat: times || anim.times,
3817 origin: element.attr(),
3818 totalOrigin: totalOrigin
3820 animationElements.push(e);
3821 if (status && !isInAnim) {
3823 e.start = new Date - ms * status;
3824 if (animationElements.length == 1) {
3828 animationElements.length == 1 && requestAnimFrame(animation);
3830 isInAnim.initstatus = status;
3831 isInAnim.start = new Date - isInAnim.ms * status;
3833 eve("anim.start." + element.id, element, anim);
3839 * Creates an animation object that can be passed to the @Element.animate or @Element.animateWith methods.
3840 * See also @Animation.delay and @Animation.repeat methods.
3844 - params (object) final attributes for the element, see also @Element.attr
3845 - ms (number) number of milliseconds for animation to run
3846 - easing (string) #optional easing type. Accept one of @Raphael.easing_formulas or CSS format: `cubic‐bezier(XX, XX, XX, XX)`
3847 - callback (function) #optional callback function. Will be called at the end of animation.
3849 = (object) @Animation
3851 R.animation = function (params, ms, easing, callback) {
3852 if (R.is(easing, "function") || !easing) {
3853 callback = callback || easing || null;
3856 params = Object(params);
3861 for (attr in params) if (params[has](attr) && toFloat(attr) != attr) {
3863 p[attr] = params[attr];
3866 return new Animation(params, ms);
3868 easing && (p.easing = easing);
3869 callback && (p.callback = callback);
3870 return new Animation({100: p}, ms);
3877 * Creates and starts animation for given element.
3881 - params (object) final attributes for the element, see also @Element.attr
3882 - ms (number) number of milliseconds for animation to run
3883 - easing (string) #optional easing type. Accept one of @Raphael.easing_formulas or CSS format: `cubic‐bezier(XX, XX, XX, XX)`
3884 - callback (function) #optional callback function. Will be called at the end of animation.
3886 - animation (object) animation object, see @Raphael.animation
3888 = (object) original element
3890 elproto.animate = function (params, ms, easing, callback) {
3892 if (element.removed) {
3893 callback && callback.call(element);
3896 var anim = params instanceof Animation ? params : R.animation(params, ms, easing, callback);
3897 runAnimation(anim, element, anim.percents[0], null, element.attr());
3904 * Sets the status of animation of the element in milliseconds. Similar to @Element.status method.
3908 - anim (object) animation object
3909 - value (number) number of milliseconds from the beginning of the animation
3911 = (object) original element if `value` is specified
3912 * Note, that during animation following events are triggered:
3914 * On each animation frame event `anim.frame.<id>`, on start `anim.start.<id>` and on end `anim.finish.<id>`.
3916 elproto.setTime = function (anim, value) {
3917 if (anim && value != null) {
3918 this.status(anim, mmin(value, anim.ms) / anim.ms);
3926 * Gets or sets the status of animation of the element.
3930 - anim (object) #optional animation object
3931 - value (number) #optional 0 – 1. If specified, method works like a setter and sets the status of a given animation to the value. This will cause animation to jump to the given position.
3935 = (array) status if `anim` is not specified. Array of objects in format:
3937 o anim: (object) animation object
3938 o status: (number) status
3941 = (object) original element if `value` is specified
3943 elproto.status = function (anim, value) {
3948 if (value != null) {
3949 runAnimation(anim, this, -1, mmin(value, 1));
3952 len = animationElements.length;
3953 for (; i < len; i++) {
3954 e = animationElements[i];
3955 if (e.el.id == this.id && (!anim || e.anim == anim)) {
3959 out.push({anim: e.anim, status: e.status});
3972 * Stops animation of the element with ability to resume it later on.
3976 - anim (object) #optional animation object
3978 = (object) original element
3980 elproto.pause = function (anim) {
3981 for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) {
3982 if (eve("anim.pause." + this.id, this, animationElements[i].anim) !== false) {
3983 animationElements[i].paused = true;
3992 * Resumes animation if it was paused with @Element.pause method.
3996 - anim (object) #optional animation object
3998 = (object) original element
4000 elproto.resume = function (anim) {
4001 for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) {
4002 var e = animationElements[i];
4003 if (eve("anim.resume." + this.id, this, e.anim) !== false) {
4005 this.status(e.anim, e.status);
4014 * Stops animation of the element.
4018 - anim (object) #optional animation object
4020 = (object) original element
4022 elproto.stop = function (anim) {
4023 for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) {
4024 if (eve("anim.stop." + this.id, this, animationElements[i].anim) !== false) {
4025 animationElements.splice(i--, 1);
4030 elproto.toString = function () {
4031 return "Rapha\xebl\u2019s object";
4035 var Set = function (items) {
4040 for (var i = 0, ii = items.length; i < ii; i++) {
4041 if (items[i] && (items[i].constructor == elproto.constructor || items[i].constructor == Set)) {
4042 this[this.items.length] = this.items[this.items.length] = items[i];
4048 setproto = Set.prototype;
4053 * Adds each argument to the current set.
4054 = (object) original element
4056 setproto.push = function () {
4059 for (var i = 0, ii = arguments.length; i < ii; i++) {
4060 item = arguments[i];
4061 if (item && (item.constructor == elproto.constructor || item.constructor == Set)) {
4062 len = this.items.length;
4063 this[len] = this.items[len] = item;
4073 * Removes last element and returns it.
4076 setproto.pop = function () {
4077 this.length && delete this[this.length--];
4078 return this.items.pop();
4084 * Executes given function for each element in the set.
4086 * If function returns `false` it will stop loop running.
4090 - callback (function) function to run
4091 - thisArg (object) context object for the callback
4092 = (object) Set object
4094 setproto.forEach = function (callback, thisArg) {
4095 for (var i = 0, ii = this.items.length; i < ii; i++) {
4096 if (callback.call(thisArg, this.items[i]) === false) {
4102 for (var method in elproto) if (elproto[has](method)) {
4103 setproto[method] = (function (methodname) {
4104 return function () {
4105 var arg = arguments;
4106 return this.forEach(function (el) {
4107 el[methodname][apply](el, arg);
4112 setproto.attr = function (name, value) {
4113 if (name && R.is(name, array) && R.is(name[0], "object")) {
4114 for (var j = 0, jj = name.length; j < jj; j++) {
4115 this.items[j].attr(name[j]);
4118 for (var i = 0, ii = this.items.length; i < ii; i++) {
4119 this.items[i].attr(name, value);
4124 setproto.clear = function () {
4125 while (this.length) {
4129 setproto.animate = function (params, ms, easing, callback) {
4130 (R.is(easing, "function") || !easing) && (callback = easing || null);
4131 var len = this.items.length,
4139 callback && (collector = function () {
4140 !--len && callback.call(set);
4142 easing = R.is(easing, string) ? easing : collector;
4143 var anim = params instanceof Animation ? params : R.animation(params, ms, easing, collector);
4144 item = this.items[--i].animate(anim);
4146 this.items[i] && !this.items[i].removed && this.items[i].animateWith(item, anim);
4150 setproto.insertAfter = function (el) {
4151 var i = this.items.length;
4153 this.items[i].insertAfter(el);
4157 setproto.getBBox = function () {
4162 for (var i = this.items.length; i--;) if (!this.items[i].removed) {
4163 var box = this.items[i].getBBox();
4166 w.push(box.x + box.width);
4167 h.push(box.y + box.height);
4169 x = mmin[apply](0, x);
4170 y = mmin[apply](0, y);
4174 width: mmax[apply](0, w) - x,
4175 height: mmax[apply](0, h) - y
4178 setproto.clone = function (s) {
4180 for (var i = 0, ii = this.items.length; i < ii; i++) {
4181 s.push(this.items[i].clone());
4185 setproto.toString = function () {
4186 return "Rapha\xebl\u2018s set";
4190 * Raphael.registerFont
4193 * Adds given font to the registered set of fonts for Raphaël. Should be used as an internal call from within Cufón’s font file.
4194 * Returns original parameter, so it could be used with chaining.
4195 # <a href="http://wiki.github.com/sorccu/cufon/about">More about Cufón and how to convert your font form TTF, OTF, etc to JavaScript file.</a>
4199 - font (object) the font to register
4200 = (object) the font you passed in
4202 | Cufon.registerFont(Raphael.registerFont({…}));
4204 R.registerFont = function (font) {
4208 this.fonts = this.fonts || {};
4214 family = font.face["font-family"];
4215 for (var prop in font.face) if (font.face[has](prop)) {
4216 fontcopy.face[prop] = font.face[prop];
4218 if (this.fonts[family]) {
4219 this.fonts[family].push(fontcopy);
4221 this.fonts[family] = [fontcopy];
4224 fontcopy.face["units-per-em"] = toInt(font.face["units-per-em"], 10);
4225 for (var glyph in font.glyphs) if (font.glyphs[has](glyph)) {
4226 var path = font.glyphs[glyph];
4227 fontcopy.glyphs[glyph] = {
4230 d: path.d && "M" + path.d.replace(/[mlcxtrv]/g, function (command) {
4231 return {l: "L", c: "C", x: "z", t: "m", r: "l", v: "c"}[command] || "M";
4235 for (var k in path.k) if (path[has](k)) {
4236 fontcopy.glyphs[glyph].k[k] = path.k[k];
4247 * Finds font object in the registered fonts by given parameters. You could specify only one word from the font name, like “Myriad” for “Myriad Pro”.
4251 - family (string) font family name or any word from it
4252 - weight (string) #optional font weight
4253 - style (string) #optional font style
4254 - stretch (string) #optional font stretch
4255 = (object) the font object
4257 | paper.print(100, 100, "Test string", paper.getFont("Times", 800), 30);
4259 paperproto.getFont = function (family, weight, style, stretch) {
4260 stretch = stretch || "normal";
4261 style = style || "normal";
4262 weight = +weight || {normal: 400, bold: 700, lighter: 300, bolder: 800}[weight] || 400;
4266 var font = R.fonts[family];
4268 var name = new RegExp("(^|\\s)" + family.replace(/[^\w\d\s+!~.:_-]/g, E) + "(\\s|$)", "i");
4269 for (var fontName in R.fonts) if (R.fonts[has](fontName)) {
4270 if (name.test(fontName)) {
4271 font = R.fonts[fontName];
4278 for (var i = 0, ii = font.length; i < ii; i++) {
4280 if (thefont.face["font-weight"] == weight && (thefont.face["font-style"] == style || !thefont.face["font-style"]) && thefont.face["font-stretch"] == stretch) {
4291 * Creates set of shapes to represent given font at given position with given size.
4292 * Result of the method is set object (see @Paper.set) which contains each letter as separate path object.
4296 - x (number) x position of the text
4297 - y (number) y position of the text
4298 - text (string) text to print
4299 - font (object) font object, see @Paper.getFont
4300 - size (number) #optional size of the font, default is `16`
4301 - origin (string) #optional could be `"baseline"` or `"middle"`, default is `"middle"`
4302 - letter_spacing (number) #optional number in range `-1..1`, default is `0`
4303 = (object) resulting set of letters
4305 | var txt = r.print(10, 50, "print", r.getFont("Museo"), 30).attr({fill: "#fff"});
4306 | // following line will paint first letter in red
4307 | txt[0].attr({fill: "#f00"});
4309 paperproto.print = function (x, y, string, font, size, origin, letter_spacing) {
4310 origin = origin || "middle"; // baseline|middle
4311 letter_spacing = mmax(mmin(letter_spacing || 0, 1), -1);
4312 var out = this.set(),
4313 letters = Str(string).split(E),
4317 R.is(font, string) && (font = this.getFont(font));
4319 scale = (size || 16) / font.face["units-per-em"];
4320 var bb = font.face.bbox.split(separator),
4322 height = +bb[1] + (origin == "baseline" ? bb[3] - bb[1] + (+font.face.descent) : (bb[3] - bb[1]) / 2);
4323 for (var i = 0, ii = letters.length; i < ii; i++) {
4324 var prev = i && font.glyphs[letters[i - 1]] || {},
4325 curr = font.glyphs[letters[i]];
4326 shift += i ? (prev.w || font.w) + (prev.k && prev.k[letters[i]] || 0) + (font.w * letter_spacing) : 0;
4327 curr && curr.d && out.push(this.path(curr.d).attr({
4330 transform: [["t", shift * scale, 0]]
4333 out.transform(["...s", scale, scale, top, height, "t", (x - top) / scale, (y - height) / scale]);
4342 * Simple format function. Replaces construction of type “`{<number>}`” to the corresponding argument.
4346 - token (string) string to format
4347 - … (string) rest of arguments will be treated as parameters for replacement
4348 = (string) formated string
4354 | // this will draw a rectangular shape equivalent to "M10,20h40v50h-40z"
4355 | paper.path(Raphael.format("M{1},{2}h{3}v{4}h{5}z", x, y, width, height, -width));
4357 R.format = function (token, params) {
4358 var args = R.is(params, array) ? [0][concat](params) : arguments;
4359 token && R.is(token, string) && args.length - 1 && (token = token.replace(formatrg, function (str, i) {
4360 return args[++i] == null ? E : args[i];
4368 * A little bit more advanced format function than @Raphael.format. Replaces construction of type “`{<name>}`” to the corresponding argument.
4372 - token (string) string to format
4373 - json (object) object which properties will be used as a replacement
4374 = (string) formated string
4376 | // this will draw a rectangular shape equivalent to "M10,20h40v50h-40z"
4377 | paper.path(Raphael.format("M{x},{y}h{dim.width}v{dim.height}h{dim['negative width']}z", {
4383 | "negative width": -40
4387 R.fullfill = (function () {
4388 var tokenRegex = /\{([^\}]+)\}/g,
4389 objNotationRegex = /(?:(?:^|\.)(.+?)(?=\[|\.|$|\()|\[('|")(.+?)\2\])(\(\))?/g, // matches .xxxxx or ["xxxxx"] to run over object properties
4390 replacer = function (all, key, obj) {
4392 key.replace(objNotationRegex, function (all, name, quote, quotedName, isFunc) {
4393 name = name || quotedName;
4398 typeof res == "function" && isFunc && (res = res());
4401 res = (res == null || res == obj ? all : res) + "";
4404 return function (str, obj) {
4405 return String(str).replace(tokenRegex, function (all, key) {
4406 return replacer(all, key, obj);
4414 * If you want to leave no trace of Raphaël (Well, Raphaël creates only one global variable `Raphael`, but anyway.) You can use `ninja` method.
4415 * Beware, that in this case plugins could stop working, because they are depending on global variable existance.
4417 = (object) Raphael object
4419 | (function (local_raphael) {
4420 | var paper = local_raphael(10, 10, 320, 200);
4422 | })(Raphael.ninja());
4424 R.ninja = function () {
4425 oldRaphael.was ? (g.win.Raphael = oldRaphael.is) : delete Raphael;
4430 [ property (object) ]
4432 * You can add your own method to elements and sets. It is wise to add a set method for each element method
4433 * you added, so you will be able to call the same method on sets too.
4435 * See also @Raphael.el.
4437 | Raphael.el.red = function () {
4438 | this.attr({fill: "#f00"});
4440 | Raphael.st.red = function () {
4441 | this.forEach(function () {
4446 | paper.set(paper.circle(100, 100, 20), paper.circle(110, 100, 20)).red();
4449 // Firefox <3.6 fix: http://webreflection.blogspot.com/2009/11/195-chars-to-help-lazy-loading.html
4450 (function (doc, loaded, f) {
4451 if (doc.readyState == null && doc.addEventListener){
4452 doc.addEventListener(loaded, f = function () {
4453 doc.removeEventListener(loaded, f, false);
4454 doc.readyState = "complete";
4456 doc.readyState = "loading";
4458 function isLoaded() {
4459 (/in/).test(doc.readyState) ? setTimeout(isLoaded, 9) : R.eve("DOMload");
4462 })(document, "DOMContentLoaded");
4464 oldRaphael.was ? (g.win.Raphael = R) : (Raphael = R);
4466 eve.on("DOMload", function () {