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 * Paper.customAttributes
105 [ property (object) ]
107 * If you have a set of attributes that you would like to represent
108 * as a function of some number you can do it easily with custom attributes:
110 | paper.customAttributes.hue = function (num) {
112 | return {fill: "hsb(" + num + ", .75, 1)"};
114 | // Custom attribute “hue” will change fill
115 | // to be given hue with fixed saturation and brightness.
116 | // Now you can use it like this:
117 | var c = paper.circle(10, 10, 10).attr({hue: .45});
118 | // or even like this:
119 | c.animate({hue: 1}, 1e3);
121 | // You could also create custom attribute
122 | // with multiple parameters:
123 | paper.customAttributes.hsb = function (h, s, b) {
124 | return {fill: "hsb(" + [h, s, b].join(",") + ")"};
126 | c.attr({hsb: ".5 .8 1"});
127 | c.animate({hsb: "1 0 .5"}, 1e3);
129 this.customAttributes = {};
132 appendChild = "appendChild",
135 supportsTouch = "createTouch" in g.doc,
140 events = "click dblclick mousedown mousemove mouseout mouseover mouseup touchstart touchmove touchend touchcancel".split(S),
142 mousedown: "touchstart",
143 mousemove: "touchmove",
146 lowerCase = Str.prototype.toLowerCase,
156 toString = "toString",
158 objectToString = Object.prototype.toString,
161 ISURL = R._ISURL = /^url\(['"]?([^\)]+?)['"]?\)$/i,
162 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,
163 isnan = {"NaN": 1, "Infinity": 1, "-Infinity": 1},
164 bezierrg = /^(?:cubic-)?bezier\(([^,]+),([^,]+),([^,]+),([^\)]+)\)/,
166 setAttribute = "setAttribute",
167 toFloat = parseFloat,
169 upperCase = Str.prototype.toUpperCase,
170 availableAttrs = R._availableAttrs = {
172 "arrow-start": "none",
174 "clip-rect": "0 0 1e9 1e9",
180 font: '10px "Arial"',
181 "font-family": '"Arial"',
183 "font-style": "normal",
187 href: "http://raphaeljs.com/",
195 "stroke-dasharray": "",
196 "stroke-linecap": "butt",
197 "stroke-linejoin": "butt",
198 "stroke-miterlimit": 0,
202 "text-anchor": "middle",
209 availableAnimAttrs = R._availableAnimAttrs = {
224 "stroke-opacity": nu,
226 transform: "transform",
231 commaSpaces = /\s*,\s*/,
232 hsrg = {hs: 1, rg: 1},
233 p2s = /,?([achlmqrstvxz]),?/gi,
234 pathCommand = /([achlmrqstvz])[\s,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?\s*,?\s*)+)/ig,
235 tCommand = /([rstm])[\s,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?\s*,?\s*)+)/ig,
236 pathValues = /(-?\d*\.?\d*(?:e[\-+]?\d+)?)\s*,?\s*/ig,
237 radial_gradient = R._radial_gradient = /^r(?:\(([^,]+?)\s*,\s*([^\)]+?)\))?/,
239 sortByKey = function (a, b) {
240 return a.key - b.key;
242 sortByNumber = function (a, b) {
243 return toFloat(a) - toFloat(b);
245 fun = function () {},
246 pipe = function (x) {
249 rectPath = R._rectPath = function (x, y, w, h, r) {
251 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"]];
253 return [["M", x, y], ["l", w, 0], ["l", 0, h], ["l", -w, 0], ["z"]];
255 ellipsePath = function (x, y, rx, ry) {
259 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"]];
261 getPath = R._getPath = {
262 path: function (el) {
263 return el.attr("path");
265 circle: function (el) {
267 return ellipsePath(a.cx, a.cy, a.r);
269 ellipse: function (el) {
271 return ellipsePath(a.cx, a.cy, a.rx, a.ry);
273 rect: function (el) {
275 return rectPath(a.x, a.y, a.width, a.height, a.r);
277 image: function (el) {
279 return rectPath(a.x, a.y, a.width, a.height);
281 text: function (el) {
282 var bbox = el._getBBox();
283 return rectPath(bbox.x, bbox.y, bbox.width, bbox.height);
286 mapPath = R.mapPath = function (path, matrix) {
290 var x, y, i, j, pathi;
291 path = path2curve(path);
292 for (i = 0, ii = path.length; i < ii; i++) {
294 for (j = 1, jj = pathi.length; j < jj; j += 2) {
295 x = matrix.x(pathi[j], pathi[j + 1]);
296 y = matrix.y(pathi[j], pathi[j + 1]);
307 [ property (string) ]
309 * Can be “SVG”, “VML” or empty, depending on browser support.
311 R.type = (g.win.SVGAngle || g.doc.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") ? "SVG" : "VML");
312 if (R.type == "VML") {
313 var d = g.doc.createElement("div"),
315 d.innerHTML = '<v:shape adj="1"/>';
317 b.style.behavior = "url(#default#VML)";
318 if (!(b && typeof b.adj == "object")) {
325 [ property (boolean) ]
327 * `true` if browser supports SVG.
331 [ property (boolean) ]
333 * `true` if browser supports VML.
335 R.svg = !(R.vml = R.type == "VML");
339 [ property (object) ]
341 * You can add your own method to the canvas. For example if you want to draw a pie chart,
342 * you can create your own pie chart function and ship it as a Raphaël plugin. To do this
343 * you need to extend the `Raphael.fn` object. Please note that you can create your own namespaces
344 * inside the `fn` object — methods will be run in the context of canvas anyway. You should alter
345 * the `fn` object before a Raphaël instance is created, otherwise it will take no effect.
347 | Raphael.fn.arrow = function (x1, y1, x2, y2, size) {
348 | return this.path( ... );
350 | // or create namespace
351 | Raphael.fn.mystuff = {
352 | arrow: function () {…},
353 | star: function () {…},
356 | var paper = Raphael(10, 10, 630, 480);
358 | paper.arrow(10, 10, 30, 30, 5).attr({fill: "#f00"});
359 | paper.mystuff.arrow();
360 | paper.mystuff.star();
362 R.fn = paperproto = Paper.prototype = R.prototype;
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;
474 * Returns RFC4122, version 4 ID
476 var createUUID = R.createUUID = (function (uuidRegEx, uuidReplacer) {
478 return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(uuidRegEx, uuidReplacer).toUpperCase();
480 })(/[xy]/g, function (c) {
481 var r = math.random() * 16 | 0,
482 v = c == "x" ? r : (r & 3 | 8);
483 return v.toString(16);
490 * Used when you need to draw in `<iframe>`. Switched window to the iframe one.
492 - newwin (window) new window object
494 R.setWindow = function (newwin) {
495 eve("setWindow", R, g.win, newwin);
497 g.doc = g.win.document;
502 var toHex = function (color) {
504 // http://dean.edwards.name/weblog/2009/10/convert-any-colour-value-to-hex-in-msie/
505 var trim = /^\s+|\s+$/g;
508 var docum = new ActiveXObject("htmlfile");
509 docum.write("<body>");
513 bod = createPopup().document.body;
515 var range = bod.createTextRange();
516 toHex = cacher(function (color) {
518 bod.style.color = Str(color).replace(trim, E);
519 var value = range.queryCommandValue("ForeColor");
520 value = ((value & 255) << 16) | (value & 65280) | ((value & 16711680) >>> 16);
521 return "#" + ("000000" + value.toString(16)).slice(-6);
527 var i = g.doc.createElement("i");
528 i.title = "Rapha\xebl Colour Picker";
529 i.style.display = "none";
530 g.doc.body.appendChild(i);
531 toHex = cacher(function (color) {
532 i.style.color = color;
533 return g.doc.defaultView.getComputedStyle(i, E).getPropertyValue("color");
538 hsbtoString = function () {
539 return "hsb(" + [this.h, this.s, this.b] + ")";
541 hsltoString = function () {
542 return "hsl(" + [this.h, this.s, this.l] + ")";
544 rgbtoString = function () {
547 prepareRGB = function (r, g, b) {
548 if (g == null && R.is(r, "object") && "r" in r && "g" in r && "b" in r) {
553 if (g == null && R.is(r, string)) {
554 var clr = R.getRGB(r);
559 if (r > 1 || g > 1 || b > 1) {
567 packageRGB = function (r, g, b, o) {
576 toString: rgbtoString
578 R.is(o, "finite") && (rgb.opacity = o);
586 * Parses the color string and returns object with all values for the given color.
588 - clr (string) color string in one of the supported formats (see @Raphael.getRGB)
589 = (object) Combined RGB & HSB object in format:
594 o hex (string) color in HTML/CSS format: #••••••,
595 o error (boolean) `true` if string can’t be parsed,
597 o s (number) saturation,
598 o v (number) value (brightness),
599 o l (number) lightness
602 R.color = function (clr) {
604 if (R.is(clr, "object") && "h" in clr && "s" in clr && "b" in clr) {
605 rgb = R.hsb2rgb(clr);
610 } else if (R.is(clr, "object") && "h" in clr && "s" in clr && "l" in clr) {
611 rgb = R.hsl2rgb(clr);
617 if (R.is(clr, "string")) {
620 if (R.is(clr, "object") && "r" in clr && "g" in clr && "b" in clr) {
621 rgb = R.rgb2hsl(clr);
625 rgb = R.rgb2hsb(clr);
629 crl.r = clr.g = clr.b = clr.h = clr.s = clr.v = clr.l = -1;
632 clr.toString = rgbtoString;
639 * Converts HSB values to RGB object.
642 - s (number) saturation
643 - v (number) value or brightness
644 = (object) RGB object in format:
649 o hex (string) color in HTML/CSS format: #••••••
652 R.hsb2rgb = function (h, s, v, o) {
653 if (this.is(h, "object") && "h" in h && "s" in h && "b" in h) {
663 X = C * (1 - abs(h % 2 - 1));
667 R += [C, X, 0, 0, X, C][h];
668 G += [X, C, C, X, 0, 0][h];
669 B += [0, 0, X, C, C, X][h];
670 return packageRGB(R, G, B, o);
676 * Converts HSL values to RGB object.
679 - s (number) saturation
680 - l (number) luminosity
681 = (object) RGB object in format:
686 o hex (string) color in HTML/CSS format: #••••••
689 R.hsl2rgb = function (h, s, l, o) {
690 if (this.is(h, "object") && "h" in h && "s" in h && "l" in h) {
695 if (h > 1 || s > 1 || l > 1) {
703 C = 2 * s * (l < .5 ? l : 1 - l);
704 X = C * (1 - abs(h % 2 - 1));
705 R = G = B = l - C / 2;
708 R += [C, X, 0, 0, X, C][h];
709 G += [X, C, C, X, 0, 0][h];
710 B += [0, 0, X, C, C, X][h];
711 return packageRGB(R, G, B, o);
717 * Converts RGB values to HSB object.
722 = (object) HSB object in format:
725 o s (number) saturation
726 o b (number) brightness
729 R.rgb2hsb = function (r, g, b) {
730 b = prepareRGB(r, g, b);
737 C = V - mmin(r, g, b);
739 V == r ? (g - b) / C :
740 V == g ? (b - r) / C + 2 :
743 H = ((H + 360) % 6) * 60 / 360;
744 S = C == 0 ? 0 : C / V;
745 return {h: H, s: S, b: V, toString: hsbtoString};
751 * Converts RGB values to HSL object.
756 = (object) HSL object in format:
759 o s (number) saturation
760 o l (number) luminosity
763 R.rgb2hsl = function (r, g, b) {
764 b = prepareRGB(r, g, b);
769 var H, S, L, M, m, C;
774 M == r ? (g - b) / C :
775 M == g ? (b - r) / C + 2 :
777 H = ((H + 360) % 6) * 60 / 360;
780 L < .5 ? C / (2 * L) :
782 return {h: H, s: S, l: L, toString: hsltoString};
784 R._path2string = function () {
785 return this.join(",").replace(p2s, "$1");
787 function repush(array, item) {
788 for (var i = 0, ii = array.length; i < ii; i++) if (array[i] === item) {
789 return array.push(array.splice(i, 1)[0]);
792 function cacher(f, scope, postprocessor) {
794 var arg = Array.prototype.slice.call(arguments, 0),
795 args = arg.join("\u2400"),
796 cache = newf.cache = newf.cache || {},
797 count = newf.count = newf.count || [];
798 if (cache[has](args)) {
800 return postprocessor ? postprocessor(cache[args]) : cache[args];
802 count.length >= 1e3 && delete cache[count.shift()];
804 cache[args] = f[apply](scope, arg);
805 return postprocessor ? postprocessor(cache[args]) : cache[args];
810 var preload = R._preload = function (src, f) {
811 var img = g.doc.createElement("img");
812 img.style.cssText = "position:absolute;left:-9999em;top-9999em";
813 img.onload = function () {
816 g.doc.body.removeChild(this);
818 img.onerror = function () {
819 g.doc.body.removeChild(this);
821 g.doc.body.appendChild(img);
825 function clrToString() {
833 * Parses colour string as RGB object
835 - colour (string) colour string in one of formats:
837 # <li>Colour name (“<code>red</code>”, “<code>green</code>”, “<code>cornflowerblue</code>”, etc)</li>
838 # <li>#••• — shortened HTML colour: (“<code>#000</code>”, “<code>#fc0</code>”, etc)</li>
839 # <li>#•••••• — full length HTML colour: (“<code>#000000</code>”, “<code>#bd2300</code>”)</li>
840 # <li>rgb(•••, •••, •••) — red, green and blue channels’ values: (“<code>rgb(200, 100, 0)</code>”)</li>
841 # <li>rgb(•••%, •••%, •••%) — same as above, but in %: (“<code>rgb(100%, 175%, 0%)</code>”)</li>
842 # <li>hsb(•••, •••, •••) — hue, saturation and brightness values: (“<code>hsb(0.5, 0.25, 1)</code>”)</li>
843 # <li>hsb(•••%, •••%, •••%) — same as above, but in %</li>
844 # <li>hsl(•••, •••, •••) — same as hsb</li>
845 # <li>hsl(•••%, •••%, •••%) — same as hsb</li>
847 = (object) RGB object in format:
852 o hex (string) color in HTML/CSS format: #••••••,
853 o error (boolean) true if string can’t be parsed
856 R.getRGB = cacher(function (colour) {
857 if (!colour || !!((colour = Str(colour)).indexOf("-") + 1)) {
858 return {r: -1, g: -1, b: -1, hex: "none", error: 1, toString: clrToString};
860 if (colour == "none") {
861 return {r: -1, g: -1, b: -1, hex: "none", toString: clrToString};
863 !(hsrg[has](colour.toLowerCase().substring(0, 2)) || colour.charAt() == "#") && (colour = toHex(colour));
871 rgb = colour.match(colourRegExp);
874 blue = toInt(rgb[2].substring(5), 16);
875 green = toInt(rgb[2].substring(3, 5), 16);
876 red = toInt(rgb[2].substring(1, 3), 16);
879 blue = toInt((t = rgb[3].charAt(3)) + t, 16);
880 green = toInt((t = rgb[3].charAt(2)) + t, 16);
881 red = toInt((t = rgb[3].charAt(1)) + t, 16);
884 values = rgb[4].split(commaSpaces);
885 red = toFloat(values[0]);
886 values[0].slice(-1) == "%" && (red *= 2.55);
887 green = toFloat(values[1]);
888 values[1].slice(-1) == "%" && (green *= 2.55);
889 blue = toFloat(values[2]);
890 values[2].slice(-1) == "%" && (blue *= 2.55);
891 rgb[1].toLowerCase().slice(0, 4) == "rgba" && (opacity = toFloat(values[3]));
892 values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
895 values = rgb[5].split(commaSpaces);
896 red = toFloat(values[0]);
897 values[0].slice(-1) == "%" && (red *= 2.55);
898 green = toFloat(values[1]);
899 values[1].slice(-1) == "%" && (green *= 2.55);
900 blue = toFloat(values[2]);
901 values[2].slice(-1) == "%" && (blue *= 2.55);
902 (values[0].slice(-3) == "deg" || values[0].slice(-1) == "\xb0") && (red /= 360);
903 rgb[1].toLowerCase().slice(0, 4) == "hsba" && (opacity = toFloat(values[3]));
904 values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
905 return R.hsb2rgb(red, green, blue, opacity);
908 values = rgb[6].split(commaSpaces);
909 red = toFloat(values[0]);
910 values[0].slice(-1) == "%" && (red *= 2.55);
911 green = toFloat(values[1]);
912 values[1].slice(-1) == "%" && (green *= 2.55);
913 blue = toFloat(values[2]);
914 values[2].slice(-1) == "%" && (blue *= 2.55);
915 (values[0].slice(-3) == "deg" || values[0].slice(-1) == "\xb0") && (red /= 360);
916 rgb[1].toLowerCase().slice(0, 4) == "hsla" && (opacity = toFloat(values[3]));
917 values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
918 return R.hsl2rgb(red, green, blue, opacity);
920 rgb = {r: red, g: green, b: blue, toString: clrToString};
921 rgb.hex = "#" + (16777216 | blue | (green << 8) | (red << 16)).toString(16).slice(1);
922 R.is(opacity, "finite") && (rgb.opacity = opacity);
925 return {r: -1, g: -1, b: -1, hex: "none", error: 1, toString: clrToString};
931 * Converts HSB values to hex representation of the colour.
934 - s (number) saturation
935 - b (number) value or brightness
936 = (string) hex representation of the colour.
938 R.hsb = cacher(function (h, s, b) {
939 return R.hsb2rgb(h, s, b).hex;
945 * Converts HSL values to hex representation of the colour.
948 - s (number) saturation
949 - l (number) luminosity
950 = (string) hex representation of the colour.
952 R.hsl = cacher(function (h, s, l) {
953 return R.hsl2rgb(h, s, l).hex;
959 * Converts RGB values to hex representation of the colour.
964 = (string) hex representation of the colour.
966 R.rgb = cacher(function (r, g, b) {
967 return "#" + (16777216 | b | (g << 8) | (r << 16)).toString(16).slice(1);
973 * On each call returns next colour in the spectrum. To reset it back to red call @Raphael.getColor.reset
975 - value (number) #optional brightness, default is `0.75`
976 = (string) hex representation of the colour.
978 R.getColor = function (value) {
979 var start = this.getColor.start = this.getColor.start || {h: 0, s: 1, b: value || .75},
980 rgb = this.hsb2rgb(start.h, start.s, start.b);
985 start.s <= 0 && (this.getColor.start = {h: 0, s: 1, b: start.b});
990 * Raphael.getColor.reset
993 * Resets spectrum position for @Raphael.getColor back to red.
995 R.getColor.reset = function () {
999 // http://schepers.cc/getting-to-the-point
1000 function catmullRom2bezier(crp) {
1002 for (var i = 0, iLen = crp.length; iLen - 2 > i; i += 2) {
1003 var p = [{x: +crp[i], y: +crp[i + 1]},
1004 {x: +crp[i], y: +crp[i + 1]},
1005 {x: +crp[i + 2], y: +crp[i + 3]},
1006 {x: +crp[i + 4], y: +crp[i + 5]}];
1007 if (iLen - 4 == i) {
1008 p[0] = {x: +crp[i - 2], y: +crp[i - 1]};
1011 p[0] = {x: +crp[i - 2], y: +crp[i - 1]};
1014 (-p[0].x + 6 * p[1].x + p[2].x) / 6,
1015 (-p[0].y + 6 * p[1].y + p[2].y) / 6,
1016 (p[1].x + 6 * p[2].x - p[3].x) / 6,
1017 (p[1].y + 6*p[2].y - p[3].y) / 6,
1026 * Raphael.parsePathString
1031 * Parses given path string into an array of arrays of path segments.
1033 - pathString (string|array) path string or array of segments (in the last case it will be returned straight away)
1034 = (array) array of segments.
1036 R.parsePathString = cacher(function (pathString) {
1040 var paramCounts = {a: 7, c: 6, h: 1, l: 2, m: 2, r: 4, q: 4, s: 4, t: 2, v: 1, z: 0},
1042 if (R.is(pathString, array) && R.is(pathString[0], array)) { // rough assumption
1043 data = pathClone(pathString);
1046 Str(pathString).replace(pathCommand, function (a, b, c) {
1048 name = b.toLowerCase();
1049 c.replace(pathValues, function (a, b) {
1050 b && params.push(+b);
1052 if (name == "m" && params.length > 2) {
1053 data.push([b][concat](params.splice(0, 2)));
1055 b = b == "m" ? "l" : "L";
1058 data.push([b][concat](params));
1059 } else while (params.length >= paramCounts[name]) {
1060 data.push([b][concat](params.splice(0, paramCounts[name])));
1061 if (!paramCounts[name]) {
1067 data.toString = R._path2string;
1071 * Raphael.parseTransformString
1076 * Parses given path string into an array of transformations.
1078 - TString (string|array) transform string or array of transformations (in the last case it will be returned straight away)
1079 = (array) array of transformations.
1081 R.parseTransformString = cacher(function (TString) {
1085 var paramCounts = {r: 3, s: 4, t: 2, m: 6},
1087 if (R.is(TString, array) && R.is(TString[0], array)) { // rough assumption
1088 data = pathClone(TString);
1091 Str(TString).replace(tCommand, function (a, b, c) {
1093 name = lowerCase.call(b);
1094 c.replace(pathValues, function (a, b) {
1095 b && params.push(+b);
1097 data.push([name][concat](params));
1100 data.toString = R._path2string;
1104 * Raphael.findDotsAtSegment
1109 * Find dot coordinates on the given cubic bezier curve at the given t.
1111 - p1x (number) x of the first point of the curve
1112 - p1y (number) y of the first point of the curve
1113 - c1x (number) x of the first anchor of the curve
1114 - c1y (number) y of the first anchor of the curve
1115 - c2x (number) x of the second anchor of the curve
1116 - c2y (number) y of the second anchor of the curve
1117 - p2x (number) x of the second point of the curve
1118 - p2y (number) y of the second point of the curve
1119 - t (number) position on the curve (0..1)
1120 = (object) point information in format:
1122 o x: (number) x coordinate of the point
1123 o y: (number) y coordinate of the point
1125 o x: (number) x coordinate of the left anchor
1126 o y: (number) y coordinate of the left anchor
1129 o x: (number) x coordinate of the right anchor
1130 o y: (number) y coordinate of the right anchor
1133 o x: (number) x coordinate of the start of the curve
1134 o y: (number) y coordinate of the start of the curve
1137 o x: (number) x coordinate of the end of the curve
1138 o y: (number) y coordinate of the end of the curve
1140 o alpha: (number) angle of the curve derivative at the point
1143 R.findDotsAtSegment = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) {
1149 x = t13 * p1x + t12 * 3 * t * c1x + t1 * 3 * t * t * c2x + t3 * p2x,
1150 y = t13 * p1y + t12 * 3 * t * c1y + t1 * 3 * t * t * c2y + t3 * p2y,
1151 mx = p1x + 2 * t * (c1x - p1x) + t2 * (c2x - 2 * c1x + p1x),
1152 my = p1y + 2 * t * (c1y - p1y) + t2 * (c2y - 2 * c1y + p1y),
1153 nx = c1x + 2 * t * (c2x - c1x) + t2 * (p2x - 2 * c2x + c1x),
1154 ny = c1y + 2 * t * (c2y - c1y) + t2 * (p2y - 2 * c2y + c1y),
1155 ax = t1 * p1x + t * c1x,
1156 ay = t1 * p1y + t * c1y,
1157 cx = t1 * c2x + t * p2x,
1158 cy = t1 * c2y + t * p2y,
1159 alpha = (90 - math.atan2(mx - nx, my - ny) * 180 / PI);
1160 (mx > nx || my < ny) && (alpha += 180);
1166 start: {x: ax, y: ay},
1167 end: {x: cx, y: cy},
1171 var pathDimensions = cacher(function (path) {
1173 return {x: 0, y: 0, width: 0, height: 0};
1175 path = path2curve(path);
1181 for (var i = 0, ii = path.length; i < ii; i++) {
1189 var dim = curveDim(x, y, p[1], p[2], p[3], p[4], p[5], p[6]);
1190 X = X[concat](dim.min.x, dim.max.x);
1191 Y = Y[concat](dim.min.y, dim.max.y);
1196 var xmin = mmin[apply](0, X),
1197 ymin = mmin[apply](0, Y);
1201 width: mmax[apply](0, X) - xmin,
1202 height: mmax[apply](0, Y) - ymin
1204 }, null, function (o) {
1212 pathClone = function (pathArray) {
1214 if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) { // rough assumption
1215 pathArray = R.parsePathString(pathArray);
1217 for (var i = 0, ii = pathArray.length; i < ii; i++) {
1219 for (var j = 0, jj = pathArray[i].length; j < jj; j++) {
1220 res[i][j] = pathArray[i][j];
1223 res.toString = R._path2string;
1226 pathToRelative = R._pathToRelative = cacher(function (pathArray) {
1227 if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) { // rough assumption
1228 pathArray = R.parsePathString(pathArray);
1236 if (pathArray[0][0] == "M") {
1237 x = pathArray[0][1];
1238 y = pathArray[0][2];
1242 res.push(["M", x, y]);
1244 for (var i = start, ii = pathArray.length; i < ii; i++) {
1245 var r = res[i] = [],
1247 if (pa[0] != lowerCase.call(pa[0])) {
1248 r[0] = lowerCase.call(pa[0]);
1256 r[6] = +(pa[6] - x).toFixed(3);
1257 r[7] = +(pa[7] - y).toFixed(3);
1260 r[1] = +(pa[1] - y).toFixed(3);
1266 for (var j = 1, jj = pa.length; j < jj; j++) {
1267 r[j] = +(pa[j] - ((j % 2) ? x : y)).toFixed(3);
1276 for (var k = 0, kk = pa.length; k < kk; k++) {
1280 var len = res[i].length;
1281 switch (res[i][0]) {
1287 x += +res[i][len - 1];
1290 y += +res[i][len - 1];
1293 x += +res[i][len - 2];
1294 y += +res[i][len - 1];
1297 res.toString = R._path2string;
1300 pathToAbsolute = R._pathToAbsolute = cacher(function (pathArray) {
1301 if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) { // rough assumption
1302 pathArray = R.parsePathString(pathArray);
1304 if (!pathArray || !pathArray.length) {
1305 return [["M", 0, 0]];
1313 if (pathArray[0][0] == "M") {
1314 x = +pathArray[0][1];
1315 y = +pathArray[0][2];
1319 res[0] = ["M", x, y];
1321 for (var r, pa, i = start, ii = pathArray.length; i < ii; i++) {
1324 if (pa[0] != upperCase.call(pa[0])) {
1325 r[0] = upperCase.call(pa[0]);
1333 r[6] = +(pa[6] + x);
1334 r[7] = +(pa[7] + y);
1343 var dots = [x, y][concat](pa.slice(1));
1344 for (var j = 2, jj = dots.length; j < jj; j++) {
1345 dots[j] = +dots[j] + x;
1346 dots[++j] = +dots[j] + y;
1349 res = res[concat](catmullRom2bezier(dots));
1355 for (j = 1, jj = pa.length; j < jj; j++) {
1356 r[j] = +pa[j] + ((j % 2) ? x : y);
1359 } else if (pa[0] == "R") {
1360 dots = [x, y][concat](pa.slice(1));
1362 res = res[concat](catmullRom2bezier(dots));
1363 r = ["R"][concat](pa.slice(-2));
1365 for (var k = 0, kk = pa.length; k < kk; k++) {
1381 mx = r[r.length - 2];
1382 my = r[r.length - 1];
1384 x = r[r.length - 2];
1385 y = r[r.length - 1];
1388 res.toString = R._path2string;
1390 }, null, pathClone),
1391 l2c = function (x1, y1, x2, y2) {
1392 return [x1, y1, x2, y2, x2, y2];
1394 q2c = function (x1, y1, ax, ay, x2, y2) {
1398 _13 * x1 + _23 * ax,
1399 _13 * y1 + _23 * ay,
1400 _13 * x2 + _23 * ax,
1401 _13 * y2 + _23 * ay,
1406 a2c = function (x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursive) {
1407 // for more information of where this math came from visit:
1408 // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
1409 var _120 = PI * 120 / 180,
1410 rad = PI / 180 * (+angle || 0),
1413 rotate = cacher(function (x, y, rad) {
1414 var X = x * math.cos(rad) - y * math.sin(rad),
1415 Y = x * math.sin(rad) + y * math.cos(rad);
1416 return {x: X, y: Y};
1419 xy = rotate(x1, y1, -rad);
1422 xy = rotate(x2, y2, -rad);
1425 var cos = math.cos(PI / 180 * angle),
1426 sin = math.sin(PI / 180 * angle),
1429 var h = (x * x) / (rx * rx) + (y * y) / (ry * ry);
1437 k = (large_arc_flag == sweep_flag ? -1 : 1) *
1438 math.sqrt(abs((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x))),
1439 cx = k * rx * y / ry + (x1 + x2) / 2,
1440 cy = k * -ry * x / rx + (y1 + y2) / 2,
1441 f1 = math.asin(((y1 - cy) / ry).toFixed(9)),
1442 f2 = math.asin(((y2 - cy) / ry).toFixed(9));
1444 f1 = x1 < cx ? PI - f1 : f1;
1445 f2 = x2 < cx ? PI - f2 : f2;
1446 f1 < 0 && (f1 = PI * 2 + f1);
1447 f2 < 0 && (f2 = PI * 2 + f2);
1448 if (sweep_flag && f1 > f2) {
1451 if (!sweep_flag && f2 > f1) {
1461 if (abs(df) > _120) {
1465 f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1);
1466 x2 = cx + rx * math.cos(f2);
1467 y2 = cy + ry * math.sin(f2);
1468 res = a2c(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [f2, f2old, cx, cy]);
1471 var c1 = math.cos(f1),
1475 t = math.tan(df / 4),
1476 hx = 4 / 3 * rx * t,
1477 hy = 4 / 3 * ry * t,
1479 m2 = [x1 + hx * s1, y1 - hy * c1],
1480 m3 = [x2 + hx * s2, y2 - hy * c2],
1482 m2[0] = 2 * m1[0] - m2[0];
1483 m2[1] = 2 * m1[1] - m2[1];
1485 return [m2, m3, m4][concat](res);
1487 res = [m2, m3, m4][concat](res).join().split(",");
1489 for (var i = 0, ii = res.length; i < ii; i++) {
1490 newres[i] = i % 2 ? rotate(res[i - 1], res[i], rad).y : rotate(res[i], res[i + 1], rad).x;
1495 findDotAtSegment = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) {
1498 x: pow(t1, 3) * p1x + pow(t1, 2) * 3 * t * c1x + t1 * 3 * t * t * c2x + pow(t, 3) * p2x,
1499 y: pow(t1, 3) * p1y + pow(t1, 2) * 3 * t * c1y + t1 * 3 * t * t * c2y + pow(t, 3) * p2y
1502 curveDim = cacher(function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) {
1503 var a = (c2x - 2 * c1x + p1x) - (p2x - 2 * c2x + c1x),
1504 b = 2 * (c1x - p1x) - 2 * (c2x - c1x),
1506 t1 = (-b + math.sqrt(b * b - 4 * a * c)) / 2 / a,
1507 t2 = (-b - math.sqrt(b * b - 4 * a * c)) / 2 / a,
1511 abs(t1) > "1e12" && (t1 = .5);
1512 abs(t2) > "1e12" && (t2 = .5);
1513 if (t1 > 0 && t1 < 1) {
1514 dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t1);
1518 if (t2 > 0 && t2 < 1) {
1519 dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t2);
1523 a = (c2y - 2 * c1y + p1y) - (p2y - 2 * c2y + c1y);
1524 b = 2 * (c1y - p1y) - 2 * (c2y - c1y);
1526 t1 = (-b + math.sqrt(b * b - 4 * a * c)) / 2 / a;
1527 t2 = (-b - math.sqrt(b * b - 4 * a * c)) / 2 / a;
1528 abs(t1) > "1e12" && (t1 = .5);
1529 abs(t2) > "1e12" && (t2 = .5);
1530 if (t1 > 0 && t1 < 1) {
1531 dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t1);
1535 if (t2 > 0 && t2 < 1) {
1536 dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t2);
1541 min: {x: mmin[apply](0, x), y: mmin[apply](0, y)},
1542 max: {x: mmax[apply](0, x), y: mmax[apply](0, y)}
1545 path2curve = R._path2curve = cacher(function (path, path2) {
1546 var p = pathToAbsolute(path),
1547 p2 = path2 && pathToAbsolute(path2),
1548 attrs = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null},
1549 attrs2 = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null},
1550 processPath = function (path, d) {
1553 return ["C", d.x, d.y, d.x, d.y, d.x, d.y];
1555 !(path[0] in {T:1, Q:1}) && (d.qx = d.qy = null);
1562 path = ["C"][concat](a2c[apply](0, [d.x, d.y][concat](path.slice(1))));
1565 nx = d.x + (d.x - (d.bx || d.x));
1566 ny = d.y + (d.y - (d.by || d.y));
1567 path = ["C", nx, ny][concat](path.slice(1));
1570 d.qx = d.x + (d.x - (d.qx || d.x));
1571 d.qy = d.y + (d.y - (d.qy || d.y));
1572 path = ["C"][concat](q2c(d.x, d.y, d.qx, d.qy, path[1], path[2]));
1577 path = ["C"][concat](q2c(d.x, d.y, path[1], path[2], path[3], path[4]));
1580 path = ["C"][concat](l2c(d.x, d.y, path[1], path[2]));
1583 path = ["C"][concat](l2c(d.x, d.y, path[1], d.y));
1586 path = ["C"][concat](l2c(d.x, d.y, d.x, path[1]));
1589 path = ["C"][concat](l2c(d.x, d.y, d.X, d.Y));
1594 fixArc = function (pp, i) {
1595 if (pp[i].length > 7) {
1599 pp.splice(i++, 0, ["C"][concat](pi.splice(0, 6)));
1602 ii = mmax(p.length, p2 && p2.length || 0);
1605 fixM = function (path1, path2, a1, a2, i) {
1606 if (path1 && path2 && path1[i][0] == "M" && path2[i][0] != "M") {
1607 path2.splice(i, 0, ["M", a2.x, a2.y]);
1612 ii = mmax(p.length, p2 && p2.length || 0);
1615 for (var i = 0, ii = mmax(p.length, p2 && p2.length || 0); i < ii; i++) {
1616 p[i] = processPath(p[i], attrs);
1618 p2 && (p2[i] = processPath(p2[i], attrs2));
1619 p2 && fixArc(p2, i);
1620 fixM(p, p2, attrs, attrs2, i);
1621 fixM(p2, p, attrs2, attrs, i);
1624 seglen = seg.length,
1625 seg2len = p2 && seg2.length;
1626 attrs.x = seg[seglen - 2];
1627 attrs.y = seg[seglen - 1];
1628 attrs.bx = toFloat(seg[seglen - 4]) || attrs.x;
1629 attrs.by = toFloat(seg[seglen - 3]) || attrs.y;
1630 attrs2.bx = p2 && (toFloat(seg2[seg2len - 4]) || attrs2.x);
1631 attrs2.by = p2 && (toFloat(seg2[seg2len - 3]) || attrs2.y);
1632 attrs2.x = p2 && seg2[seg2len - 2];
1633 attrs2.y = p2 && seg2[seg2len - 1];
1635 return p2 ? [p, p2] : p;
1636 }, null, pathClone),
1637 parseDots = R._parseDots = cacher(function (gradient) {
1639 for (var i = 0, ii = gradient.length; i < ii; i++) {
1641 par = gradient[i].match(/^([^:]*):?([\d\.]*)/);
1642 dot.color = R.getRGB(par[1]);
1643 if (dot.color.error) {
1646 dot.color = dot.color.hex;
1647 par[2] && (dot.offset = par[2] + "%");
1650 for (i = 1, ii = dots.length - 1; i < ii; i++) {
1651 if (!dots[i].offset) {
1652 var start = toFloat(dots[i - 1].offset || 0),
1654 for (var j = i + 1; j < ii; j++) {
1655 if (dots[j].offset) {
1656 end = dots[j].offset;
1665 var d = (end - start) / (j - i + 1);
1666 for (; i < j; i++) {
1668 dots[i].offset = start + "%";
1674 tear = R._tear = function (el, paper) {
1675 el == paper.top && (paper.top = el.prev);
1676 el == paper.bottom && (paper.bottom = el.next);
1677 el.next && (el.next.prev = el.prev);
1678 el.prev && (el.prev.next = el.next);
1680 tofront = R._tofront = function (el, paper) {
1681 if (paper.top === el) {
1686 el.prev = paper.top;
1687 paper.top.next = el;
1690 toback = R._toback = function (el, paper) {
1691 if (paper.bottom === el) {
1695 el.next = paper.bottom;
1697 paper.bottom.prev = el;
1700 insertafter = R._insertafter = function (el, el2, paper) {
1702 el2 == paper.top && (paper.top = el);
1703 el2.next && (el2.next.prev = el);
1708 insertbefore = R._insertbefore = function (el, el2, paper) {
1710 el2 == paper.bottom && (paper.bottom = el);
1711 el2.prev && (el2.prev.next = el);
1716 removed = function (methodname) {
1717 return function () {
1718 throw new Error("Rapha\xebl: you are calling to method \u201c" + methodname + "\u201d of removed object");
1721 extractTransform = R._extractTransform = function (el, tstr) {
1723 return el._.transform;
1725 tstr = Str(tstr).replace(/\.{3}|\u2026/g, el._.transform || E);
1726 var tdata = R.parseTransformString(tstr),
1734 _.transform = tdata || [];
1736 for (var i = 0, ii = tdata.length; i < ii; i++) {
1740 t[0] = Str(t[0]).toLowerCase();
1741 if (t[0] == "t" && tlen == 3) {
1742 m.translate(t[1], t[2]);
1743 } else if (t[0] == "r") {
1745 bb = bb || el.getBBox(1);
1746 m.rotate(t[1], bb.x + bb.width / 2, bb.y + bb.height / 2);
1748 } else if (tlen == 4) {
1749 m.rotate(t[1], t[2], t[3]);
1752 } else if (t[0] == "s") {
1753 if (tlen == 2 || tlen == 3) {
1754 bb = bb || el.getBBox(1);
1755 m.scale(t[1], t[tlen - 1], bb.x + bb.width / 2, bb.y + bb.height / 2);
1758 } else if (tlen == 5) {
1759 m.scale(t[1], t[2], t[3], t[4]);
1763 } else if (t[0] == "m" && tlen == 7) {
1764 m.add(t[1], t[2], t[3], t[4], t[5], t[6]);
1779 if (sx == 1 && sy == 1 && !deg && _.bbox) {
1786 getEmpty = function (item) {
1788 case "t": return ["t", 0, 0];
1789 case "m": return ["m", 1, 0, 0, 1, 0, 0];
1790 case "r": if (item.length == 4) {
1791 return ["r", 0, item[2], item[3]];
1795 case "s": if (item.length == 5) {
1796 return ["s", 1, 1, item[3], item[4]];
1797 } else if (item.length == 3) {
1804 equaliseTransform = R._equaliseTransform = function (t1, t2) {
1805 t2 = Str(t2).replace(/\.{3}|\u2026/g, t1);
1806 t1 = R.parseTransformString(t1) || [];
1807 t2 = R.parseTransformString(t2) || [];
1808 var maxlength = mmax(t1.length, t2.length),
1813 for (; i < maxlength; i++) {
1814 tt1 = t1[i] || getEmpty(t2[i]);
1815 tt2 = t2[i] || getEmpty(tt1);
1816 if ((tt1[0] != tt2[0]) ||
1817 (tt1[0] == "r" && (tt1[2] != tt2[2] || tt1[3] != tt2[3])) ||
1818 (tt1[0] == "s" && (tt1[3] != tt2[3] || tt1[4] != tt2[4]))
1824 for (j = 0, jj = mmax(tt1.length, tt2.length); j < jj; j++) {
1825 j in tt1 && (from[i][j] = tt1[j]);
1826 j in tt2 && (to[i][j] = tt2[j]);
1834 R._getContainer = function (x, y, w, h) {
1836 container = h == null && !R.is(x, "object") ? g.doc.getElementById(x) : x;
1837 if (container == null) {
1840 if (container.tagName) {
1843 container: container,
1844 width: container.style.pixelWidth || container.offsetWidth,
1845 height: container.style.pixelHeight || container.offsetHeight
1849 container: container,
1864 * Raphael.pathToRelative
1869 * Converts path to relative form
1871 - pathString (string|array) path string or array of segments
1872 = (array) array of segments.
1874 R.pathToRelative = pathToRelative;
1877 * Raphael.path2curve
1882 * Converts path to a new path where all segments are cubic bezier curves.
1884 - pathString (string|array) path string or array of segments
1885 = (array) array of segments.
1887 R.path2curve = path2curve;
1894 * Returns matrix based on given parameters.
1904 R.matrix = function (a, b, c, d, e, f) {
1905 return new Matrix(a, b, c, d, e, f);
1907 function Matrix(a, b, c, d, e, f) {
1924 (function (matrixproto) {
1929 * Adds given matrix to existing one.
1938 - matrix (object) @Matrix
1940 matrixproto.add = function (a, b, c, d, e, f) {
1941 var out = [[], [], []],
1942 m = [[this.a, this.c, this.e], [this.b, this.d, this.f], [0, 0, 1]],
1943 matrix = [[a, c, e], [b, d, f], [0, 0, 1]],
1946 if (a && a instanceof Matrix) {
1947 matrix = [[a.a, a.c, a.e], [a.b, a.d, a.f], [0, 0, 1]];
1950 for (x = 0; x < 3; x++) {
1951 for (y = 0; y < 3; y++) {
1953 for (z = 0; z < 3; z++) {
1954 res += m[x][z] * matrix[z][y];
1970 * Returns inverted version of the matrix
1973 matrixproto.invert = function () {
1975 x = me.a * me.d - me.b * me.c;
1976 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);
1982 * Returns copy of the matrix
1985 matrixproto.clone = function () {
1986 return new Matrix(this.a, this.b, this.c, this.d, this.e, this.f);
1992 * Translate the matrix
1997 matrixproto.translate = function (x, y) {
1998 this.add(1, 0, 0, 1, x, y);
2007 - y (number) #optional
2008 - cx (number) #optional
2009 - cy (number) #optional
2011 matrixproto.scale = function (x, y, cx, cy) {
2012 y == null && (y = x);
2013 (cx || cy) && this.add(1, 0, 0, 1, cx, cy);
2014 this.add(x, 0, 0, y, 0, 0);
2015 (cx || cy) && this.add(1, 0, 0, 1, -cx, -cy);
2021 * Rotates the matrix
2027 matrixproto.rotate = function (a, x, y) {
2031 var cos = +math.cos(a).toFixed(9),
2032 sin = +math.sin(a).toFixed(9);
2033 this.add(cos, sin, -sin, cos, x, y);
2034 this.add(1, 0, 0, 1, -x, -y);
2040 * Return x coordinate for given point after transformation described by the matrix. See also @Matrix.y
2046 matrixproto.x = function (x, y) {
2047 return x * this.a + y * this.c + this.e;
2053 * Return y coordinate for given point after transformation described by the matrix. See also @Matrix.x
2059 matrixproto.y = function (x, y) {
2060 return x * this.b + y * this.d + this.f;
2062 matrixproto.get = function (i) {
2063 return +this[Str.fromCharCode(97 + i)].toFixed(4);
2065 matrixproto.toString = function () {
2067 "matrix(" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)].join() + ")" :
2068 [this.get(0), this.get(2), this.get(1), this.get(3), 0, 0].join();
2070 matrixproto.toFilter = function () {
2071 return "progid:DXImageTransform.Microsoft.Matrix(M11=" + this.get(0) +
2072 ", M12=" + this.get(2) + ", M21=" + this.get(1) + ", M22=" + this.get(3) +
2073 ", Dx=" + this.get(4) + ", Dy=" + this.get(5) + ", sizingmethod='auto expand')";
2075 matrixproto.offset = function () {
2076 return [this.e.toFixed(4), this.f.toFixed(4)];
2079 return a[0] * a[0] + a[1] * a[1];
2081 function normalize(a) {
2082 var mag = math.sqrt(norm(a));
2083 a[0] && (a[0] /= mag);
2084 a[1] && (a[1] /= mag);
2090 * Splits matrix into primitive transformations
2091 = (object) in format:
2092 o dx (number) translation by x
2093 o dy (number) translation by y
2094 o scalex (number) scale by x
2095 o scaley (number) scale by y
2096 o shear (number) shear
2097 o rotate (number) rotation in deg
2098 o isSimple (boolean) could it be represented via simple transformations
2100 matrixproto.split = function () {
2107 var row = [[this.a, this.c], [this.b, this.d]];
2108 out.scalex = math.sqrt(norm(row[0]));
2111 out.shear = row[0][0] * row[1][0] + row[0][1] * row[1][1];
2112 row[1] = [row[1][0] - row[0][0] * out.shear, row[1][1] - row[0][1] * out.shear];
2114 out.scaley = math.sqrt(norm(row[1]));
2116 out.shear /= out.scaley;
2119 var sin = -row[0][1],
2122 out.rotate = R.deg(math.acos(cos));
2124 out.rotate = 360 - out.rotate;
2127 out.rotate = R.deg(math.asin(sin));
2130 out.isSimple = !+out.shear.toFixed(9) && (out.scalex.toFixed(9) == out.scaley.toFixed(9) || !out.rotate);
2131 out.isSuperSimple = !+out.shear.toFixed(9) && out.scalex.toFixed(9) == out.scaley.toFixed(9) && !out.rotate;
2132 out.noRotation = !+out.shear.toFixed(9) && !out.rotate;
2136 * Matrix.toTransformString
2139 * Return transform string that represents given matrix
2140 = (string) transform string
2142 matrixproto.toTransformString = function () {
2143 var s = this.split();
2145 return "t" + [s.dx, s.dy] + "s" + [s.scalex, s.scaley, 0, 0] + "r" + [s.rotate, 0, 0];
2147 return "m" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)];
2150 })(Matrix.prototype);
2152 // WebKit rendering bug workaround method
2153 var version = navigator.userAgent.match(/Version\/(.*?)\s/) || navigator.userAgent.match(/Chrome\/(\d+)/);
2154 if ((navigator.vendor == "Apple Computer, Inc.") && (version && version[1] < 4 || navigator.platform.slice(0, 2) == "iP") ||
2155 (navigator.vendor == "Google Inc." && version && version[1] < 8)) {
2160 * There is an inconvenient rendering bug in Safari (WebKit):
2161 * sometimes the rendering should be forced.
2162 * This method should help with dealing with this bug.
2164 paperproto.safari = function () {
2165 var rect = this.rect(-99, -99, this.width + 99, this.height + 99).attr({stroke: "none"});
2166 setTimeout(function () {rect.remove();});
2169 paperproto.safari = fun;
2172 var preventDefault = function () {
2173 this.returnValue = false;
2175 preventTouch = function () {
2176 return this.originalEvent.preventDefault();
2178 stopPropagation = function () {
2179 this.cancelBubble = true;
2181 stopTouch = function () {
2182 return this.originalEvent.stopPropagation();
2184 addEvent = (function () {
2185 if (g.doc.addEventListener) {
2186 return function (obj, type, fn, element) {
2187 var realName = supportsTouch && touchMap[type] ? touchMap[type] : type,
2189 var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
2190 scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft,
2191 x = e.clientX + scrollX,
2192 y = e.clientY + scrollY;
2193 if (supportsTouch && touchMap[has](type)) {
2194 for (var i = 0, ii = e.targetTouches && e.targetTouches.length; i < ii; i++) {
2195 if (e.targetTouches[i].target == obj) {
2197 e = e.targetTouches[i];
2198 e.originalEvent = olde;
2199 e.preventDefault = preventTouch;
2200 e.stopPropagation = stopTouch;
2205 return fn.call(element, e, x, y);
2207 obj.addEventListener(realName, f, false);
2208 return function () {
2209 obj.removeEventListener(realName, f, false);
2213 } else if (g.doc.attachEvent) {
2214 return function (obj, type, fn, element) {
2215 var f = function (e) {
2216 e = e || g.win.event;
2217 var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
2218 scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft,
2219 x = e.clientX + scrollX,
2220 y = e.clientY + scrollY;
2221 e.preventDefault = e.preventDefault || preventDefault;
2222 e.stopPropagation = e.stopPropagation || stopPropagation;
2223 return fn.call(element, e, x, y);
2225 obj.attachEvent("on" + type, f);
2226 var detacher = function () {
2227 obj.detachEvent("on" + type, f);
2235 dragMove = function (e) {
2238 scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
2239 scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft,
2244 if (supportsTouch) {
2245 var i = e.touches.length,
2248 touch = e.touches[i];
2249 if (touch.identifier == dragi.el._drag.id) {
2252 (e.originalEvent ? e.originalEvent : e).preventDefault();
2259 var node = dragi.el.node,
2261 next = node.nextSibling,
2262 parent = node.parentNode,
2263 display = node.style.display;
2264 g.win.opera && parent.removeChild(node);
2265 node.style.display = "none";
2266 o = dragi.el.paper.getElementByPoint(x, y);
2267 node.style.display = display;
2268 g.win.opera && (next ? parent.insertBefore(node, next) : parent.appendChild(node));
2269 o && eve("drag.over." + dragi.el.id, dragi.el, o);
2272 eve("drag.move." + dragi.el.id, dragi.move_scope || dragi.el, x - dragi.el._drag.x, y - dragi.el._drag.y, x, y, e);
2275 dragUp = function (e) {
2276 R.unmousemove(dragMove).unmouseup(dragUp);
2277 var i = drag.length,
2281 dragi.el._drag = {};
2282 eve("drag.end." + dragi.el.id, dragi.end_scope || dragi.start_scope || dragi.move_scope || dragi.el, e);
2288 [ property (object) ]
2290 * You can add your own method to elements. This is usefull when you want to hack default functionality or
2291 * want to wrap some common transformation or attributes in one method. In difference to canvas methods,
2292 * you can redefine element method at any time. Expending element methods wouldn’t affect set.
2294 | Raphael.el.red = function () {
2295 | this.attr({fill: "#f00"});
2298 | paper.circle(100, 100, 20).red();
2300 elproto = R.el = {};
2305 * Adds event handler for click for the element.
2307 - handler (function) handler for the event
2314 * Removes event handler for click for the element.
2316 - handler (function) handler for the event
2324 * Adds event handler for double click for the element.
2326 - handler (function) handler for the event
2330 * Element.undblclick
2333 * Removes event handler for double click for the element.
2335 - handler (function) handler for the event
2343 * Adds event handler for mousedown for the element.
2345 - handler (function) handler for the event
2349 * Element.unmousedown
2352 * Removes event handler for mousedown for the element.
2354 - handler (function) handler for the event
2362 * Adds event handler for mousemove for the element.
2364 - handler (function) handler for the event
2368 * Element.unmousemove
2371 * Removes event handler for mousemove for the element.
2373 - handler (function) handler for the event
2381 * Adds event handler for mouseout for the element.
2383 - handler (function) handler for the event
2387 * Element.unmouseout
2390 * Removes event handler for mouseout for the element.
2392 - handler (function) handler for the event
2400 * Adds event handler for mouseover for the element.
2402 - handler (function) handler for the event
2406 * Element.unmouseover
2409 * Removes event handler for mouseover for the element.
2411 - handler (function) handler for the event
2419 * Adds event handler for mouseup for the element.
2421 - handler (function) handler for the event
2428 * Removes event handler for mouseup for the element.
2430 - handler (function) handler for the event
2435 * Element.touchstart
2438 * Adds event handler for touchstart for the element.
2440 - handler (function) handler for the event
2444 * Element.untouchstart
2447 * Removes event handler for touchstart for the element.
2449 - handler (function) handler for the event
2457 * Adds event handler for touchmove for the element.
2459 - handler (function) handler for the event
2463 * Element.untouchmove
2466 * Removes event handler for touchmove for the element.
2468 - handler (function) handler for the event
2476 * Adds event handler for touchend for the element.
2478 - handler (function) handler for the event
2482 * Element.untouchend
2485 * Removes event handler for touchend for the element.
2487 - handler (function) handler for the event
2492 * Element.touchcancel
2495 * Adds event handler for touchcancel for the element.
2497 - handler (function) handler for the event
2501 * Element.untouchcancel
2504 * Removes event handler for touchcancel for the element.
2506 - handler (function) handler for the event
2509 for (var i = events.length; i--;) {
2510 (function (eventName) {
2511 R[eventName] = elproto[eventName] = function (fn, scope) {
2512 if (R.is(fn, "function")) {
2513 this.events = this.events || [];
2514 this.events.push({name: eventName, f: fn, unbind: addEvent(this.shape || this.node || g.doc, eventName, fn, scope || this)});
2518 R["un" + eventName] = elproto["un" + eventName] = function (fn) {
2519 var events = this.events,
2521 while (l--) if (events[l].name == eventName && events[l].f == fn) {
2523 events.splice(l, 1);
2524 !events.length && delete this.events;
2536 * Adds or retrieves given value asociated with given key.
2538 * See also @Element.removeData
2540 - key (string) key to store data
2541 - value (any) #optional value to store
2543 * or, if value is not specified:
2546 | for (var i = 0, i < 5, i++) {
2547 | paper.circle(10 + 15 * i, 10, 10)
2548 | .attr({fill: "#000"})
2550 | .click(function () {
2551 | alert(this.data("i"));
2555 elproto.data = function (key, value) {
2556 var data = eldata[this.id] = eldata[this.id] || {};
2557 if (arguments.length == 1) {
2558 if (R.is(key, "object")) {
2559 for (var i in key) if (key[has](i)) {
2560 this.data(i, key[i]);
2564 eve("data.get." + this.id, this, data[key], key);
2568 eve("data.set." + this.id, this, value, key);
2572 * Element.removeData
2575 * Removes value associated with an element by given key.
2576 * If key is not provided, removes all the data of the element.
2578 - key (string) #optional key
2581 elproto.removeData = function (key) {
2583 eldata[this.id] = {};
2585 eldata[this.id] && delete eldata[this.id][key];
2593 * Adds event handlers for hover for the element.
2595 - f_in (function) handler for hover in
2596 - f_out (function) handler for hover out
2597 - icontext (object) #optional context for hover in handler
2598 - ocontext (object) #optional context for hover out handler
2601 elproto.hover = function (f_in, f_out, scope_in, scope_out) {
2602 return this.mouseover(f_in, scope_in).mouseout(f_out, scope_out || scope_in);
2608 * Removes event handlers for hover for the element.
2610 - f_in (function) handler for hover in
2611 - f_out (function) handler for hover out
2614 elproto.unhover = function (f_in, f_out) {
2615 return this.unmouseover(f_in).unmouseout(f_out);
2621 * Adds event handlers for drag of the element.
2623 - onmove (function) handler for moving
2624 - onstart (function) handler for drag start
2625 - onend (function) handler for drag end
2626 - mcontext (object) #optional context for moving handler
2627 - scontext (object) #optional context for drag start handler
2628 - econtext (object) #optional context for drag end handler
2629 * Additionaly following `drag` events will be triggered: `drag.start.<id>` on start,
2630 * `drag.end.<id>` on end and `drag.move.<id>` on every move. When element will be dragged over another element
2631 * `drag.over.<id>` will be fired as well.
2633 * Start event and start handler will be called in specified context or in context of the element with following parameters:
2634 o x (number) x position of the mouse
2635 o y (number) y position of the mouse
2636 o event (object) DOM event object
2637 * Move event and move handler will be called in specified context or in context of the element with following parameters:
2638 o dx (number) shift by x from the start point
2639 o dy (number) shift by y from the start point
2640 o x (number) x position of the mouse
2641 o y (number) y position of the mouse
2642 o event (object) DOM event object
2643 * End event and end handler will be called in specified context or in context of the element with following parameters:
2644 o event (object) DOM event object
2647 elproto.drag = function (onmove, onstart, onend, move_scope, start_scope, end_scope) {
2649 (e.originalEvent || e).preventDefault();
2650 var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
2651 scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft;
2652 this._drag.x = e.clientX + scrollX;
2653 this._drag.y = e.clientY + scrollY;
2654 this._drag.id = e.identifier;
2655 !drag.length && R.mousemove(dragMove).mouseup(dragUp);
2656 drag.push({el: this, move_scope: move_scope, start_scope: start_scope, end_scope: end_scope});
2657 onstart && eve.on("drag.start." + this.id, onstart);
2658 onmove && eve.on("drag.move." + this.id, onmove);
2659 onend && eve.on("drag.end." + this.id, onend);
2660 eve("drag.start." + this.id, start_scope || move_scope || this, e.clientX + scrollX, e.clientY + scrollY, e);
2663 this.mousedown(start);
2667 * Element.onDragOver
2670 * Shortcut for assigning event handler for `drag.over.<id>` event, where id is id of the element (see @Element.id).
2672 - f (function) handler for event, first argument would be the element you are dragging over
2674 elproto.onDragOver = function (f) {
2675 f ? eve.on("drag.over." + this.id, f) : eve.unbind("drag.over." + this.id);
2681 * Removes all drag event handlers from given element.
2683 elproto.undrag = function () {
2684 var i = drag.length;
2685 while (i--) if (drag[i].el == this) {
2686 R.unmousedown(drag[i].start);
2687 drag.splice(i++, 1);
2688 eve.unbind("drag.*." + this.id);
2690 !drag.length && R.unmousemove(dragMove).unmouseup(dragUp);
2700 - x (number) x coordinate of the centre
2701 - y (number) y coordinate of the centre
2703 = (object) Raphaël element object with type “circle”
2706 | var c = paper.circle(50, 50, 40);
2708 paperproto.circle = function (x, y, r) {
2709 var out = R._engine.circle(this, x || 0, y || 0, r || 0);
2710 this.__set__ && this.__set__.push(out);
2717 * Draws a rectangle.
2721 - x (number) x coordinate of the top left corner
2722 - y (number) y coordinate of the top left corner
2723 - width (number) width
2724 - height (number) height
2725 - r (number) #optional radius for rounded corners, default is 0
2726 = (object) Raphaël element object with type “rect”
2729 | // regular rectangle
2730 | var c = paper.rect(10, 10, 50, 50);
2731 | // rectangle with rounded corners
2732 | var c = paper.rect(40, 40, 50, 50, 10);
2734 paperproto.rect = function (x, y, w, h, r) {
2735 var out = R._engine.rect(this, x || 0, y || 0, w || 0, h || 0, r || 0);
2736 this.__set__ && this.__set__.push(out);
2747 - x (number) x coordinate of the centre
2748 - y (number) y coordinate of the centre
2749 - rx (number) horizontal radius
2750 - ry (number) vertical radius
2751 = (object) Raphaël element object with type “ellipse”
2754 | var c = paper.ellipse(50, 50, 40, 20);
2756 paperproto.ellipse = function (x, y, rx, ry) {
2757 var out = R._engine.ellipse(this, x || 0, y || 0, rx || 0, ry || 0);
2758 this.__set__ && this.__set__.push(out);
2765 * Creates a path element by given path data string.
2767 - pathString (string) #optional path string in SVG format.
2768 * Path string consists of one-letter commands, followed by comma seprarated arguments in numercal form. Example:
2770 * Here we can see two commands: “M”, with arguments `(10, 20)` and “L” with arguments `(30, 40)`. Upper case letter mean command is absolute, lower case—relative.
2772 # <p>Here is short list of commands available, for more details see <a href="http://www.w3.org/TR/SVG/paths.html#PathData" title="Details of a path's data attribute's format are described in the SVG specification.">SVG path string format</a>.</p>
2773 # <table><thead><tr><th>Command</th><th>Name</th><th>Parameters</th></tr></thead><tbody>
2774 # <tr><td>M</td><td>moveto</td><td>(x y)+</td></tr>
2775 # <tr><td>Z</td><td>closepath</td><td>(none)</td></tr>
2776 # <tr><td>L</td><td>lineto</td><td>(x y)+</td></tr>
2777 # <tr><td>H</td><td>horizontal lineto</td><td>x+</td></tr>
2778 # <tr><td>V</td><td>vertical lineto</td><td>y+</td></tr>
2779 # <tr><td>C</td><td>curveto</td><td>(x1 y1 x2 y2 x y)+</td></tr>
2780 # <tr><td>S</td><td>smooth curveto</td><td>(x2 y2 x y)+</td></tr>
2781 # <tr><td>Q</td><td>quadratic Bézier curveto</td><td>(x1 y1 x y)+</td></tr>
2782 # <tr><td>T</td><td>smooth quadratic Bézier curveto</td><td>(x y)+</td></tr>
2783 # <tr><td>A</td><td>elliptical arc</td><td>(rx ry x-axis-rotation large-arc-flag sweep-flag x y)+</td></tr>
2784 # <tr><td>R</td><td><a href="http://en.wikipedia.org/wiki/Catmull–Rom_spline#Catmull.E2.80.93Rom_spline">Catmull-Rom curveto</a>*</td><td>x1 y1 (x y)+</td></tr></tbody></table>
2785 * * “Catmull-Rom curveto” is a not standard SVG command and added in 2.0 to make life easier.
2787 | var c = paper.path("M10 10L90 90");
2788 | // draw a diagonal line:
2789 | // move to 10,10, line to 90,90
2791 paperproto.path = function (pathString) {
2792 pathString && !R.is(pathString, string) && !R.is(pathString[0], array) && (pathString += E);
2793 var out = R._engine.path(R.format[apply](R, arguments), this);
2794 this.__set__ && this.__set__.push(out);
2801 * Embeds an image into the surface.
2805 - src (string) URI of the source image
2806 - x (number) x coordinate position
2807 - y (number) y coordinate position
2808 - width (number) width of the image
2809 - height (number) height of the image
2810 = (object) Raphaël element object with type “image”
2813 | var c = paper.image("apple.png", 10, 10, 80, 80);
2815 paperproto.image = function (src, x, y, w, h) {
2816 var out = R._engine.image(this, src || "about:blank", x || 0, y || 0, w || 0, h || 0);
2817 this.__set__ && this.__set__.push(out);
2824 * Draws a text string. If you need line breaks, put “\n” in the string.
2828 - x (number) x coordinate position
2829 - y (number) y coordinate position
2830 - text (string) The text string to draw
2831 = (object) Raphaël element object with type “text”
2834 | var t = paper.text(50, 50, "Raphaël\nkicks\nbutt!");
2836 paperproto.text = function (x, y, text) {
2837 var out = R._engine.text(this, x || 0, y || 0, Str(text));
2838 this.__set__ && this.__set__.push(out);
2845 * Creates array-like object to keep and operate several elements at once.
2846 * Warning: it doesn’t create any elements for itself in the page, it just groups existing elements.
2847 * Sets act as pseudo elements — all methods available to an element can be used on a set.
2848 = (object) array-like object that represents set of elements
2851 | var st = paper.set();
2853 | paper.circle(10, 10, 5),
2854 | paper.circle(30, 10, 5)
2856 | st.attr({fill: "red"}); // changes the fill of both circles
2858 paperproto.set = function (itemsArray) {
2859 !R.is(itemsArray, "array") && (itemsArray = Array.prototype.splice.call(arguments, 0, arguments.length));
2860 var out = new Set(itemsArray);
2861 this.__set__ && this.__set__.push(out);
2868 * Creates @Paper.set. All elements that will be created after calling this method and before calling
2869 * @Paper.setFinish will be added to the set.
2873 | paper.circle(10, 10, 5),
2874 | paper.circle(30, 10, 5)
2875 | var st = paper.setFinish();
2876 | st.attr({fill: "red"}); // changes the fill of both circles
2878 paperproto.setStart = function (set) {
2879 this.__set__ = set || this.set();
2885 * See @Paper.setStart. This method finishes catching and returns resulting set.
2889 paperproto.setFinish = function (set) {
2890 var out = this.__set__;
2891 delete this.__set__;
2898 * If you need to change dimensions of the canvas call this method
2902 - width (number) new width of the canvas
2903 - height (number) new height of the canvas
2905 | var st = paper.set();
2907 | paper.circle(10, 10, 5),
2908 | paper.circle(30, 10, 5)
2910 | st.attr({fill: "red"});
2912 paperproto.setSize = function (width, height) {
2913 return R._engine.setSize.call(this, width, height);
2919 * Sets the view box of the paper. Practically it gives you ability to zoom and pan whole paper surface by
2920 * specifying new boundaries.
2924 - x (number) new x position, default is `0`
2925 - y (number) new y position, default is `0`
2926 - w (number) new width of the canvas
2927 - h (number) new height of the canvas
2928 - fit (boolean) `true` if you want graphics to fit into new boundary box
2930 paperproto.setViewBox = function (x, y, w, h, fit) {
2931 return R._engine.setViewBox.call(this, x, y, w, h, fit);
2937 * Points to the topmost element on the paper
2943 * Points to the bottom element on the paper
2945 paperproto.top = paperproto.bottom = null;
2950 * Points to the @Raphael object/function
2952 paperproto.raphael = R;
2953 var getOffset = function (elem) {
2954 var box = elem.getBoundingClientRect(),
2955 doc = elem.ownerDocument,
2957 docElem = doc.documentElement,
2958 clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0,
2959 top = box.top + (g.win.pageYOffset || docElem.scrollTop || body.scrollTop ) - clientTop,
2960 left = box.left + (g.win.pageXOffset || docElem.scrollLeft || body.scrollLeft) - clientLeft;
2967 * Paper.getElementByPoint
2970 * Returns you topmost element under given point.
2972 = (object) Raphaël element object
2975 - x (number) x coordinate from the top left corner of the window
2976 - y (number) y coordinate from the top left corner of the window
2978 | paper.getElementByPoint(mouseX, mouseY).attr({stroke: "#f00"});
2980 paperproto.getElementByPoint = function (x, y) {
2983 target = g.doc.elementFromPoint(x, y);
2984 if (g.win.opera && target.tagName == "svg") {
2985 var so = getOffset(svg),
2986 sr = svg.createSVGRect();
2989 sr.width = sr.height = 1;
2990 var hits = svg.getIntersectionList(sr, null);
2992 target = hits[hits.length - 1];
2998 while (target.parentNode && target != svg.parentNode && !target.raphael) {
2999 target = target.parentNode;
3001 target == paper.canvas.parentNode && (target = svg);
3002 target = target && target.raphael ? paper.getById(target.raphaelid) : null;
3009 * Returns you element by its internal ID.
3014 = (object) Raphaël element object
3016 paperproto.getById = function (id) {
3017 var bot = this.bottom;
3030 * Executes given function for each element on the paper
3032 * If callback function returns `false` it will stop loop running.
3036 - callback (function) function to run
3037 - thisArg (object) context object for the callback
3038 = (object) Paper object
3040 paperproto.forEach = function (callback, thisArg) {
3041 var bot = this.bottom;
3043 if (callback.call(thisArg, bot) === false) {
3051 return this.x + S + this.y;
3053 function x_y_w_h() {
3054 return this.x + S + this.y + S + this.width + " \xd7 " + this.height;
3060 * Return bounding box for a given element
3064 - isWithoutTransform (boolean) flag, `true` if you want to have bounding box before transformations. Default is `false`.
3065 = (object) Bounding box object:
3067 o x: (number) top left corner x
3068 o y: (number) top left corner y
3069 o width: (number) width
3070 o height: (number) height
3073 elproto.getBBox = function (isWithoutTransform) {
3078 if (isWithoutTransform) {
3079 if (_.dirty || !_.bboxwt) {
3080 this.realPath = getPath[this.type](this);
3081 _.bboxwt = pathDimensions(this.realPath);
3082 _.bboxwt.toString = x_y_w_h;
3087 if (_.dirty || _.dirtyT || !_.bbox) {
3088 if (_.dirty || !this.realPath) {
3090 this.realPath = getPath[this.type](this);
3092 _.bbox = pathDimensions(mapPath(this.realPath, this.matrix));
3093 _.bbox.toString = x_y_w_h;
3094 _.dirty = _.dirtyT = 0;
3102 = (object) clone of a given element
3105 elproto.clone = function () {
3109 var out = this.paper[this.type]().attr(this.attr());
3110 this.__set__ && this.__set__.push(out);
3117 * Return set of elements that create glow-like effect around given element. See @Paper.set.
3119 * Note: Glow is not connected to the element. If you change element attributes it won’t adjust itself.
3123 - glow (object) #optional parameters object with all properties optional:
3125 o width (number) size of the glow, default is `10`
3126 o fill (boolean) will it be filled, default is `false`
3127 o opacity (number) opacity, default is `0.5`
3128 o offsetx (number) horizontal offset, default is `0`
3129 o offsety (number) vertical offset, default is `0`
3130 o color (string) glow colour, default is `black`
3132 = (object) @Paper.set of elements that represents glow
3134 elproto.glow = function (glow) {
3135 if (this.type == "text") {
3140 width: (glow.width || 10) + (+this.attr("stroke-width") || 1),
3141 fill: glow.fill || false,
3142 opacity: glow.opacity || .5,
3143 offsetx: glow.offsetx || 0,
3144 offsety: glow.offsety || 0,
3145 color: glow.color || "#000"
3150 path = this.realPath || getPath[this.type](this);
3151 path = this.matrix ? mapPath(path, this.matrix) : path;
3152 for (var i = 1; i < c + 1; i++) {
3153 out.push(r.path(path).attr({
3155 fill: s.fill ? s.color : "none",
3156 "stroke-linejoin": "round",
3157 "stroke-linecap": "round",
3158 "stroke-width": +(s.width / c * i).toFixed(3),
3159 opacity: +(s.opacity / c).toFixed(3)
3162 return out.insertBefore(this).translate(s.offsetx, s.offsety);
3164 var curveslengths = {},
3165 getPointAtSegmentLength = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length) {
3168 name = [p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y].join(),
3169 cache = curveslengths[name],
3171 !cache && (curveslengths[name] = cache = {data: []});
3172 cache.timer && clearTimeout(cache.timer);
3173 cache.timer = setTimeout(function () {delete curveslengths[name];}, 2e3);
3174 if (length != null && !cache.precision) {
3175 var total = getPointAtSegmentLength(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y);
3176 cache.precision = ~~total * 10;
3179 precision = cache.precision || precision;
3180 for (var i = 0; i < precision + 1; i++) {
3181 if (cache.data[i * precision]) {
3182 dot = cache.data[i * precision];
3184 dot = R.findDotsAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, i / precision);
3185 cache.data[i * precision] = dot;
3187 i && (len += pow(pow(old.x - dot.x, 2) + pow(old.y - dot.y, 2), .5));
3188 if (length != null && len >= length) {
3193 if (length == null) {
3197 getLengthFactory = function (istotal, subpath) {
3198 return function (path, length, onlystart) {
3199 path = path2curve(path);
3200 var x, y, p, l, sp = "", subpaths = {}, point,
3202 for (var i = 0, ii = path.length; i < ii; i++) {
3208 l = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6]);
3209 if (len + l > length) {
3210 if (subpath && !subpaths.start) {
3211 point = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6], length - len);
3212 sp += ["C" + point.start.x, point.start.y, point.m.x, point.m.y, point.x, point.y];
3213 if (onlystart) {return sp;}
3214 subpaths.start = sp;
3215 sp = ["M" + point.x, point.y + "C" + point.n.x, point.n.y, point.end.x, point.end.y, p[5], p[6]].join();
3221 if (!istotal && !subpath) {
3222 point = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6], length - len);
3223 return {x: point.x, y: point.y, alpha: point.alpha};
3230 sp += p.shift() + p;
3233 point = istotal ? len : subpath ? subpaths : R.findDotsAtSegment(x, y, p[0], p[1], p[2], p[3], p[4], p[5], 1);
3234 point.alpha && (point = {x: point.x, y: point.y, alpha: point.alpha});
3238 var getTotalLength = getLengthFactory(1),
3239 getPointAtLength = getLengthFactory(),
3240 getSubpathsAtLength = getLengthFactory(0, 1);
3242 * Raphael.getTotalLength
3245 * Returns length of the given path in pixels.
3249 - path (string) SVG path string.
3253 R.getTotalLength = getTotalLength;
3255 * Raphael.getPointAtLength
3258 * Return coordinates of the point located at the given length on the given path.
3262 - path (string) SVG path string
3265 = (object) representation of the point:
3267 o x: (number) x coordinate
3268 o y: (number) y coordinate
3269 o alpha: (number) angle of derivative
3272 R.getPointAtLength = getPointAtLength;
3274 * Raphael.getSubpath
3277 * Return subpath of a given path from given length to given length.
3281 - path (string) SVG path string
3282 - from (number) position of the start of the segment
3283 - to (number) position of the end of the segment
3285 = (string) pathstring for the segment
3287 R.getSubpath = function (path, from, to) {
3288 if (this.getTotalLength(path) - to < 1e-6) {
3289 return getSubpathsAtLength(path, from).end;
3291 var a = getSubpathsAtLength(path, to, 1);
3292 return from ? getSubpathsAtLength(a, from).end : a;
3295 * Element.getTotalLength
3298 * Returns length of the path in pixels. Only works for element of “path” type.
3301 elproto.getTotalLength = function () {
3302 if (this.type != "path") {return;}
3303 if (this.node.getTotalLength) {
3304 return this.node.getTotalLength();
3306 return getTotalLength(this.attrs.path);
3309 * Element.getPointAtLength
3312 * Return coordinates of the point located at the given length on the given path. Only works for element of “path” type.
3318 = (object) representation of the point:
3320 o x: (number) x coordinate
3321 o y: (number) y coordinate
3322 o alpha: (number) angle of derivative
3325 elproto.getPointAtLength = function (length) {
3326 if (this.type != "path") {return;}
3327 return getPointAtLength(this.attrs.path, length);
3330 * Element.getSubpath
3333 * Return subpath of a given element from given length to given length. Only works for element of “path” type.
3337 - from (number) position of the start of the segment
3338 - to (number) position of the end of the segment
3340 = (string) pathstring for the segment
3342 elproto.getSubpath = function (from, to) {
3343 if (this.type != "path") {return;}
3344 return R.getSubpath(this.attrs.path, from, to);
3347 * Raphael.easing_formulas
3350 * Object that contains easing formulas for animation. You could extend it with your own. By default it has following list of easing:
3353 # <li>“<” or “easeIn” or “ease-in”</li>
3354 # <li>“>” or “easeOut” or “ease-out”</li>
3355 # <li>“<>” or “easeInOut” or “ease-in-out”</li>
3356 # <li>“backIn” or “back-in”</li>
3357 # <li>“backOut” or “back-out”</li>
3358 # <li>“elastic”</li>
3361 # <p>See also <a href="http://raphaeljs.com/easing.html">Easing demo</a>.</p>
3363 var ef = R.easing_formulas = {
3364 linear: function (n) {
3373 "<>": function (n) {
3374 var q = .48 - n / 1.04,
3375 Q = math.sqrt(.1734 + q * q),
3377 X = pow(abs(x), 1 / 3) * (x < 0 ? -1 : 1),
3379 Y = pow(abs(y), 1 / 3) * (y < 0 ? -1 : 1),
3381 return (1 - t) * 3 * t * t + t * t * t;
3383 backIn: function (n) {
3385 return n * n * ((s + 1) * n - s);
3387 backOut: function (n) {
3390 return n * n * ((s + 1) * n + s) + 1;
3392 elastic: function (n) {
3396 return pow(2, -10 * n) * math.sin((n - .075) * (2 * PI) / .3) + 1;
3398 bounce: function (n) {
3407 l = s * n * n + .75;
3409 if (n < (2.5 / p)) {
3411 l = s * n * n + .9375;
3414 l = s * n * n + .984375;
3421 ef.easeIn = ef["ease-in"] = ef["<"];
3422 ef.easeOut = ef["ease-out"] = ef[">"];
3423 ef.easeInOut = ef["ease-in-out"] = ef["<>"];
3424 ef["back-in"] = ef.backIn;
3425 ef["back-out"] = ef.backOut;
3427 var animationElements = [],
3428 requestAnimFrame = window.requestAnimationFrame ||
3429 window.webkitRequestAnimationFrame ||
3430 window.mozRequestAnimationFrame ||
3431 window.oRequestAnimationFrame ||
3432 window.msRequestAnimationFrame ||
3433 function (callback) {
3434 setTimeout(callback, 16);
3436 animation = function () {
3437 var Now = +new Date,
3439 for (; l < animationElements.length; l++) {
3440 var e = animationElements[l];
3441 if (e.el.removed || e.paused) {
3444 var time = Now - e.start,
3455 time = (e.initstatus * e.anim.top - e.prev) / (e.percent - e.prev) * ms;
3456 e.status = e.initstatus;
3457 delete e.initstatus;
3458 e.stop && animationElements.splice(l--, 1);
3460 e.status = (e.prev + (e.percent - e.prev) * (time / ms)) / e.anim.top;
3466 var pos = easing(time / ms);
3467 for (var attr in from) if (from[has](attr)) {
3468 switch (availableAnimAttrs[attr]) {
3470 now = +from[attr] + pos * ms * diff[attr];
3474 upto255(round(from[attr].r + pos * ms * diff[attr].r)),
3475 upto255(round(from[attr].g + pos * ms * diff[attr].g)),
3476 upto255(round(from[attr].b + pos * ms * diff[attr].b))
3481 for (var i = 0, ii = from[attr].length; i < ii; i++) {
3482 now[i] = [from[attr][i][0]];
3483 for (var j = 1, jj = from[attr][i].length; j < jj; j++) {
3484 now[i][j] = +from[attr][i][j] + pos * ms * diff[attr][i][j];
3486 now[i] = now[i].join(S);
3491 if (diff[attr].real) {
3493 for (i = 0, ii = from[attr].length; i < ii; i++) {
3494 now[i] = [from[attr][i][0]];
3495 for (j = 1, jj = from[attr][i].length; j < jj; j++) {
3496 now[i][j] = from[attr][i][j] + pos * ms * diff[attr][i][j];
3500 var get = function (i) {
3501 return +from[attr][i] + pos * ms * diff[attr][i];
3503 // now = [["r", get(2), 0, 0], ["t", get(3), get(4)], ["s", get(0), get(1), 0, 0]];
3504 now = [["m", get(0), get(1), get(2), get(3), get(4), get(5)]];
3508 if (attr == "clip-rect") {
3512 now[i] = +from[attr][i] + pos * ms * diff[attr][i];
3517 var from2 = [].concat(from[attr]);
3519 i = that.paper.customAttributes[attr].length;
3521 now[i] = +from2[i] + pos * ms * diff[attr][i];
3528 (function (id, that, anim) {
3529 setTimeout(function () {
3530 eve("anim.frame." + id, that, anim);
3532 })(that.id, that, e.anim);
3534 (function(f, el, a) {
3535 setTimeout(function() {
3536 eve("anim.frame." + el.id, el, a);
3537 eve("anim.finish." + el.id, el, a);
3538 R.is(f, "function") && f.call(el);
3540 })(e.callback, that, e.anim);
3542 animationElements.splice(l--, 1);
3543 if (e.repeat > 1 && !e.next) {
3544 runAnimation(e.anim, e.el, e.anim.percents[0], null, e.totalOrigin, e.repeat - 1);
3546 if (e.next && !e.stop) {
3547 runAnimation(e.anim, e.el, e.next, null, e.totalOrigin, e.repeat);
3551 R.svg && that && that.paper && that.paper.safari();
3552 animationElements.length && requestAnimFrame(animation);
3554 upto255 = function (color) {
3555 return color > 255 ? 255 : color < 0 ? 0 : color;
3558 * Element.animateWith
3561 * Acts similar to @Element.animate, but ensure that given animation runs in sync with another given element.
3565 - element (object) element to sync with
3566 - anim (object) animation to sync with
3567 - params (object) #optional final attributes for the element, see also @Element.attr
3568 - ms (number) #optional number of milliseconds for animation to run
3569 - easing (string) #optional easing type. Accept on of @Raphael.easing_formulas or CSS format: `cubic‐bezier(XX, XX, XX, XX)`
3570 - callback (function) #optional callback function. Will be called at the end of animation.
3572 - element (object) element to sync with
3573 - anim (object) animation to sync with
3574 - animation (object) #optional animation object, see @Raphael.animation
3576 = (object) original element
3578 elproto.animateWith = function (element, anim, params, ms, easing, callback) {
3579 var a = params ? R.animation(params, ms, easing, callback) : anim;
3580 status = element.status(anim);
3581 return this.animate(a).status(a, status * anim.ms / a.ms);
3583 function CubicBezierAtTime(t, p1x, p1y, p2x, p2y, duration) {
3585 bx = 3 * (p2x - p1x) - cx,
3588 by = 3 * (p2y - p1y) - cy,
3590 function sampleCurveX(t) {
3591 return ((ax * t + bx) * t + cx) * t;
3593 function solve(x, epsilon) {
3594 var t = solveCurveX(x, epsilon);
3595 return ((ay * t + by) * t + cy) * t;
3597 function solveCurveX(x, epsilon) {
3598 var t0, t1, t2, x2, d2, i;
3599 for(t2 = x, i = 0; i < 8; i++) {
3600 x2 = sampleCurveX(t2) - x;
3601 if (abs(x2) < epsilon) {
3604 d2 = (3 * ax * t2 + 2 * bx) * t2 + cx;
3605 if (abs(d2) < 1e-6) {
3620 x2 = sampleCurveX(t2);
3621 if (abs(x2 - x) < epsilon) {
3629 t2 = (t1 - t0) / 2 + t0;
3633 return solve(t, 1 / (200 * duration));
3635 elproto.onAnimation = function (f) {
3636 f ? eve.on("anim.frame." + this.id, f) : eve.unbind("anim.frame." + this.id);
3639 function Animation(anim, ms) {
3645 for (var attr in anim) if (anim[has](attr)) {
3646 newAnim[toFloat(attr)] = anim[attr];
3647 percents.push(toFloat(attr));
3649 percents.sort(sortByNumber);
3651 this.anim = newAnim;
3652 this.top = percents[percents.length - 1];
3653 this.percents = percents;
3659 * Creates a copy of existing animation object with given delay.
3663 - delay (number) number of ms to pass between animation start and actual animation
3665 = (object) new altered Animation object
3666 | var anim = Raphael.animation({cx: 10, cy: 20}, 2e3);
3667 | circle1.animate(anim); // run the given animation immediately
3668 | circle2.animate(anim.delay(500)); // run the given animation after 500 ms
3670 Animation.prototype.delay = function (delay) {
3671 var a = new Animation(this.anim, this.ms);
3672 a.times = this.times;
3673 a.del = +delay || 0;
3680 * Creates a copy of existing animation object with given repetition.
3684 - repeat (number) number iterations of animation. For infinite animation pass `Infinity`
3686 = (object) new altered Animation object
3688 Animation.prototype.repeat = function (times) {
3689 var a = new Animation(this.anim, this.ms);
3691 a.times = math.floor(mmax(times, 0)) || 1;
3694 function runAnimation(anim, element, percent, status, totalOrigin, times) {
3695 percent = toFloat(percent);
3708 for (i = 0, ii = animationElements.length; i < ii; i++) {
3709 var e = animationElements[i];
3710 if (e.el.id == element.id && e.anim == anim) {
3711 if (e.percent != percent) {
3712 animationElements.splice(i, 1);
3717 element.attr(e.totalOrigin);
3722 status = +to; // NaN
3724 for (var i = 0, ii = anim.percents.length; i < ii; i++) {
3725 if (anim.percents[i] == percent || anim.percents[i] > status * anim.top) {
3726 percent = anim.percents[i];
3727 prev = anim.percents[i - 1] || 0;
3728 ms = ms / anim.top * (percent - prev);
3729 next = anim.percents[i + 1];
3730 params = anim.anim[percent];
3732 } else if (status) {
3733 element.attr(anim.anim[anim.percents[i]]);
3740 for (attr in params) if (params[has](attr)) {
3741 if (availableAnimAttrs[has](attr) || element.paper.customAttributes[has](attr)) {
3742 from[attr] = element.attr(attr);
3743 (from[attr] == null) && (from[attr] = availableAttrs[attr]);
3744 to[attr] = params[attr];
3745 switch (availableAnimAttrs[attr]) {
3747 diff[attr] = (to[attr] - from[attr]) / ms;
3750 from[attr] = R.getRGB(from[attr]);
3751 var toColour = R.getRGB(to[attr]);
3753 r: (toColour.r - from[attr].r) / ms,
3754 g: (toColour.g - from[attr].g) / ms,
3755 b: (toColour.b - from[attr].b) / ms
3759 var pathes = path2curve(from[attr], to[attr]),
3761 from[attr] = pathes[0];
3763 for (i = 0, ii = from[attr].length; i < ii; i++) {
3764 diff[attr][i] = [0];
3765 for (var j = 1, jj = from[attr][i].length; j < jj; j++) {
3766 diff[attr][i][j] = (toPath[i][j] - from[attr][i][j]) / ms;
3772 eq = equaliseTransform(_[attr], to[attr]);
3774 from[attr] = eq.from;
3777 diff[attr].real = true;
3778 for (i = 0, ii = from[attr].length; i < ii; i++) {
3779 diff[attr][i] = [from[attr][i][0]];
3780 for (j = 1, jj = from[attr][i].length; j < jj; j++) {
3781 diff[attr][i][j] = (to[attr][i][j] - from[attr][i][j]) / ms;
3785 var m = (element.matrix || new Matrix),
3787 _: {transform: _.transform},
3788 getBBox: function () {
3789 return element.getBBox(1);
3800 extractTransform(to2, to[attr]);
3801 to[attr] = to2._.transform;
3803 (to2.matrix.a - m.a) / ms,
3804 (to2.matrix.b - m.b) / ms,
3805 (to2.matrix.c - m.c) / ms,
3806 (to2.matrix.d - m.d) / ms,
3807 (to2.matrix.e - m.e) / ms,
3808 (to2.matrix.e - m.f) / ms
3810 // from[attr] = [_.sx, _.sy, _.deg, _.dx, _.dy];
3811 // var to2 = {_:{}, getBBox: function () { return element.getBBox(); }};
3812 // extractTransform(to2, to[attr]);
3814 // (to2._.sx - _.sx) / ms,
3815 // (to2._.sy - _.sy) / ms,
3816 // (to2._.deg - _.deg) / ms,
3817 // (to2._.dx - _.dx) / ms,
3818 // (to2._.dy - _.dy) / ms
3823 var values = Str(params[attr]).split(separator),
3824 from2 = Str(from[attr]).split(separator);
3825 if (attr == "clip-rect") {
3830 diff[attr][i] = (values[i] - from[attr][i]) / ms;
3836 values = [].concat(params[attr]);
3837 from2 = [].concat(from[attr]);
3839 i = element.paper.customAttributes[attr].length;
3841 diff[attr][i] = ((values[i] || 0) - (from2[i] || 0)) / ms;
3847 var easing = params.easing,
3848 easyeasy = R.easing_formulas[easing];
3850 easyeasy = Str(easing).match(bezierrg);
3851 if (easyeasy && easyeasy.length == 5) {
3852 var curve = easyeasy;
3853 easyeasy = function (t) {
3854 return CubicBezierAtTime(t, +curve[1], +curve[2], +curve[3], +curve[4], ms);
3860 timestamp = params.start || anim.start || +new Date;
3864 timestamp: timestamp,
3865 start: timestamp + (anim.del || 0),
3867 initstatus: status || 0,
3875 callback: params.callback,
3878 repeat: times || anim.times,
3879 origin: element.attr(),
3880 totalOrigin: totalOrigin
3882 animationElements.push(e);
3883 if (status && !isInAnim && !isInAnimSet) {
3885 e.start = new Date - ms * status;
3886 if (animationElements.length == 1) {
3891 e.start = new Date - e.ms * status;
3893 animationElements.length == 1 && requestAnimFrame(animation);
3895 isInAnim.initstatus = status;
3896 isInAnim.start = new Date - isInAnim.ms * status;
3898 eve("anim.start." + element.id, element, anim);
3904 * Creates an animation object that can be passed to the @Element.animate or @Element.animateWith methods.
3905 * See also @Animation.delay and @Animation.repeat methods.
3909 - params (object) final attributes for the element, see also @Element.attr
3910 - ms (number) number of milliseconds for animation to run
3911 - easing (string) #optional easing type. Accept one of @Raphael.easing_formulas or CSS format: `cubic‐bezier(XX, XX, XX, XX)`
3912 - callback (function) #optional callback function. Will be called at the end of animation.
3914 = (object) @Animation
3916 R.animation = function (params, ms, easing, callback) {
3917 if (params instanceof Animation) {
3920 if (R.is(easing, "function") || !easing) {
3921 callback = callback || easing || null;
3924 params = Object(params);
3929 for (attr in params) if (params[has](attr) && toFloat(attr) != attr && toFloat(attr) + "%" != attr) {
3931 p[attr] = params[attr];
3934 return new Animation(params, ms);
3936 easing && (p.easing = easing);
3937 callback && (p.callback = callback);
3938 return new Animation({100: p}, ms);
3945 * Creates and starts animation for given element.
3949 - params (object) final attributes for the element, see also @Element.attr
3950 - ms (number) number of milliseconds for animation to run
3951 - easing (string) #optional easing type. Accept one of @Raphael.easing_formulas or CSS format: `cubic‐bezier(XX, XX, XX, XX)`
3952 - callback (function) #optional callback function. Will be called at the end of animation.
3954 - animation (object) animation object, see @Raphael.animation
3956 = (object) original element
3958 elproto.animate = function (params, ms, easing, callback) {
3960 if (element.removed) {
3961 callback && callback.call(element);
3964 var anim = params instanceof Animation ? params : R.animation(params, ms, easing, callback);
3965 runAnimation(anim, element, anim.percents[0], null, element.attr());
3972 * Sets the status of animation of the element in milliseconds. Similar to @Element.status method.
3976 - anim (object) animation object
3977 - value (number) number of milliseconds from the beginning of the animation
3979 = (object) original element if `value` is specified
3980 * Note, that during animation following events are triggered:
3982 * On each animation frame event `anim.frame.<id>`, on start `anim.start.<id>` and on end `anim.finish.<id>`.
3984 elproto.setTime = function (anim, value) {
3985 if (anim && value != null) {
3986 this.status(anim, mmin(value, anim.ms) / anim.ms);
3994 * Gets or sets the status of animation of the element.
3998 - anim (object) #optional animation object
3999 - 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.
4003 = (array) status if `anim` is not specified. Array of objects in format:
4005 o anim: (object) animation object
4006 o status: (number) status
4009 = (object) original element if `value` is specified
4011 elproto.status = function (anim, value) {
4016 if (value != null) {
4017 runAnimation(anim, this, -1, mmin(value, 1));
4020 len = animationElements.length;
4021 for (; i < len; i++) {
4022 e = animationElements[i];
4023 if (e.el.id == this.id && (!anim || e.anim == anim)) {
4043 * Stops animation of the element with ability to resume it later on.
4047 - anim (object) #optional animation object
4049 = (object) original element
4051 elproto.pause = function (anim) {
4052 for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) {
4053 if (eve("anim.pause." + this.id, this, animationElements[i].anim) !== false) {
4054 animationElements[i].paused = true;
4063 * Resumes animation if it was paused with @Element.pause method.
4067 - anim (object) #optional animation object
4069 = (object) original element
4071 elproto.resume = function (anim) {
4072 for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) {
4073 var e = animationElements[i];
4074 if (eve("anim.resume." + this.id, this, e.anim) !== false) {
4076 this.status(e.anim, e.status);
4085 * Stops animation of the element.
4089 - anim (object) #optional animation object
4091 = (object) original element
4093 elproto.stop = function (anim) {
4094 for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) {
4095 if (eve("anim.stop." + this.id, this, animationElements[i].anim) !== false) {
4096 animationElements.splice(i--, 1);
4101 elproto.toString = function () {
4102 return "Rapha\xebl\u2019s object";
4106 var Set = function (items) {
4111 for (var i = 0, ii = items.length; i < ii; i++) {
4112 if (items[i] && (items[i].constructor == elproto.constructor || items[i].constructor == Set)) {
4113 this[this.items.length] = this.items[this.items.length] = items[i];
4119 setproto = Set.prototype;
4124 * Adds each argument to the current set.
4125 = (object) original element
4127 setproto.push = function () {
4130 for (var i = 0, ii = arguments.length; i < ii; i++) {
4131 item = arguments[i];
4132 if (item && (item.constructor == elproto.constructor || item.constructor == Set)) {
4133 len = this.items.length;
4134 this[len] = this.items[len] = item;
4144 * Removes last element and returns it.
4147 setproto.pop = function () {
4148 this.length && delete this[this.length--];
4149 return this.items.pop();
4155 * Executes given function for each element in the set.
4157 * If function returns `false` it will stop loop running.
4161 - callback (function) function to run
4162 - thisArg (object) context object for the callback
4163 = (object) Set object
4165 setproto.forEach = function (callback, thisArg) {
4166 for (var i = 0, ii = this.items.length; i < ii; i++) {
4167 if (callback.call(thisArg, this.items[i]) === false) {
4173 for (var method in elproto) if (elproto[has](method)) {
4174 setproto[method] = (function (methodname) {
4175 return function () {
4176 var arg = arguments;
4177 return this.forEach(function (el) {
4178 el[methodname][apply](el, arg);
4183 setproto.attr = function (name, value) {
4184 if (name && R.is(name, array) && R.is(name[0], "object")) {
4185 for (var j = 0, jj = name.length; j < jj; j++) {
4186 this.items[j].attr(name[j]);
4189 for (var i = 0, ii = this.items.length; i < ii; i++) {
4190 this.items[i].attr(name, value);
4199 * Removeds all elements from the set
4201 setproto.clear = function () {
4202 while (this.length) {
4210 * Removes given element from the set
4214 - index (number) position of the deletion
4215 - count (number) number of element to remove
4216 - insertion… (object) #optional elements to insert
4217 = (object) set elements that were deleted
4219 setproto.splice = function (index, count, insertion) {
4220 index = index < 0 ? mmax(this.length + index, 0) : index;
4221 count = mmax(0, mmin(this.length - index, count));
4226 for (i = 2; i < arguments.length; i++) {
4227 args.push(arguments[i]);
4229 for (i = 0; i < count; i++) {
4230 todel.push(this[index + i]);
4232 for (; i < this.length - index; i++) {
4233 tail.push(this[index + i]);
4235 var arglen = args.length;
4236 for (i = 0; i < arglen + tail.length; i++) {
4237 this.items[index + i] = this[index + i] = i < arglen ? args[i] : tail[i - arglen];
4239 i = this.items.length = this.length -= count - arglen;
4243 return new Set(todel);
4249 * Removes given element from the set
4253 - element (object) element to remove
4254 = (boolean) `true` if object was found & removed from the set
4256 setproto.exclude = function (el) {
4257 for (var i = 0, ii = this.length, found; i < ii; i++) if (found || this[i] == el) {
4258 this[i] = this[i + 1];
4267 setproto.animate = function (params, ms, easing, callback) {
4268 (R.is(easing, "function") || !easing) && (callback = easing || null);
4269 var len = this.items.length,
4277 callback && (collector = function () {
4278 !--len && callback.call(set);
4280 easing = R.is(easing, string) ? easing : collector;
4281 var anim = R.animation(params, ms, easing, collector);
4282 item = this.items[--i].animate(anim);
4284 this.items[i] && !this.items[i].removed && this.items[i].animateWith(item, anim);
4288 setproto.insertAfter = function (el) {
4289 var i = this.items.length;
4291 this.items[i].insertAfter(el);
4295 setproto.getBBox = function () {
4300 for (var i = this.items.length; i--;) if (!this.items[i].removed) {
4301 var box = this.items[i].getBBox();
4304 w.push(box.x + box.width);
4305 h.push(box.y + box.height);
4307 x = mmin[apply](0, x);
4308 y = mmin[apply](0, y);
4312 width: mmax[apply](0, w) - x,
4313 height: mmax[apply](0, h) - y
4316 setproto.clone = function (s) {
4318 for (var i = 0, ii = this.items.length; i < ii; i++) {
4319 s.push(this.items[i].clone());
4323 setproto.toString = function () {
4324 return "Rapha\xebl\u2018s set";
4328 * Raphael.registerFont
4331 * 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.
4332 * Returns original parameter, so it could be used with chaining.
4333 # <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>
4337 - font (object) the font to register
4338 = (object) the font you passed in
4340 | Cufon.registerFont(Raphael.registerFont({…}));
4342 R.registerFont = function (font) {
4346 this.fonts = this.fonts || {};
4352 family = font.face["font-family"];
4353 for (var prop in font.face) if (font.face[has](prop)) {
4354 fontcopy.face[prop] = font.face[prop];
4356 if (this.fonts[family]) {
4357 this.fonts[family].push(fontcopy);
4359 this.fonts[family] = [fontcopy];
4362 fontcopy.face["units-per-em"] = toInt(font.face["units-per-em"], 10);
4363 for (var glyph in font.glyphs) if (font.glyphs[has](glyph)) {
4364 var path = font.glyphs[glyph];
4365 fontcopy.glyphs[glyph] = {
4368 d: path.d && "M" + path.d.replace(/[mlcxtrv]/g, function (command) {
4369 return {l: "L", c: "C", x: "z", t: "m", r: "l", v: "c"}[command] || "M";
4373 for (var k in path.k) if (path[has](k)) {
4374 fontcopy.glyphs[glyph].k[k] = path.k[k];
4385 * 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”.
4389 - family (string) font family name or any word from it
4390 - weight (string) #optional font weight
4391 - style (string) #optional font style
4392 - stretch (string) #optional font stretch
4393 = (object) the font object
4395 | paper.print(100, 100, "Test string", paper.getFont("Times", 800), 30);
4397 paperproto.getFont = function (family, weight, style, stretch) {
4398 stretch = stretch || "normal";
4399 style = style || "normal";
4400 weight = +weight || {normal: 400, bold: 700, lighter: 300, bolder: 800}[weight] || 400;
4404 var font = R.fonts[family];
4406 var name = new RegExp("(^|\\s)" + family.replace(/[^\w\d\s+!~.:_-]/g, E) + "(\\s|$)", "i");
4407 for (var fontName in R.fonts) if (R.fonts[has](fontName)) {
4408 if (name.test(fontName)) {
4409 font = R.fonts[fontName];
4416 for (var i = 0, ii = font.length; i < ii; i++) {
4418 if (thefont.face["font-weight"] == weight && (thefont.face["font-style"] == style || !thefont.face["font-style"]) && thefont.face["font-stretch"] == stretch) {
4429 * Creates set of shapes to represent given font at given position with given size.
4430 * Result of the method is set object (see @Paper.set) which contains each letter as separate path object.
4434 - x (number) x position of the text
4435 - y (number) y position of the text
4436 - text (string) text to print
4437 - font (object) font object, see @Paper.getFont
4438 - size (number) #optional size of the font, default is `16`
4439 - origin (string) #optional could be `"baseline"` or `"middle"`, default is `"middle"`
4440 - letter_spacing (number) #optional number in range `-1..1`, default is `0`
4441 = (object) resulting set of letters
4443 | var txt = r.print(10, 50, "print", r.getFont("Museo"), 30).attr({fill: "#fff"});
4444 | // following line will paint first letter in red
4445 | txt[0].attr({fill: "#f00"});
4447 paperproto.print = function (x, y, string, font, size, origin, letter_spacing) {
4448 origin = origin || "middle"; // baseline|middle
4449 letter_spacing = mmax(mmin(letter_spacing || 0, 1), -1);
4450 var out = this.set(),
4451 letters = Str(string).split(E),
4455 R.is(font, string) && (font = this.getFont(font));
4457 scale = (size || 16) / font.face["units-per-em"];
4458 var bb = font.face.bbox.split(separator),
4460 height = +bb[1] + (origin == "baseline" ? bb[3] - bb[1] + (+font.face.descent) : (bb[3] - bb[1]) / 2);
4461 for (var i = 0, ii = letters.length; i < ii; i++) {
4462 var prev = i && font.glyphs[letters[i - 1]] || {},
4463 curr = font.glyphs[letters[i]];
4464 shift += i ? (prev.w || font.w) + (prev.k && prev.k[letters[i]] || 0) + (font.w * letter_spacing) : 0;
4465 curr && curr.d && out.push(this.path(curr.d).attr({
4468 transform: [["t", shift * scale, 0]]
4471 out.transform(["...s", scale, scale, top, height, "t", (x - top) / scale, (y - height) / scale]);
4480 * Simple format function. Replaces construction of type “`{<number>}`” to the corresponding argument.
4484 - token (string) string to format
4485 - … (string) rest of arguments will be treated as parameters for replacement
4486 = (string) formated string
4492 | // this will draw a rectangular shape equivalent to "M10,20h40v50h-40z"
4493 | paper.path(Raphael.format("M{1},{2}h{3}v{4}h{5}z", x, y, width, height, -width));
4495 R.format = function (token, params) {
4496 var args = R.is(params, array) ? [0][concat](params) : arguments;
4497 token && R.is(token, string) && args.length - 1 && (token = token.replace(formatrg, function (str, i) {
4498 return args[++i] == null ? E : args[i];
4506 * A little bit more advanced format function than @Raphael.format. Replaces construction of type “`{<name>}`” to the corresponding argument.
4510 - token (string) string to format
4511 - json (object) object which properties will be used as a replacement
4512 = (string) formated string
4514 | // this will draw a rectangular shape equivalent to "M10,20h40v50h-40z"
4515 | paper.path(Raphael.format("M{x},{y}h{dim.width}v{dim.height}h{dim['negative width']}z", {
4521 | "negative width": -40
4525 R.fullfill = (function () {
4526 var tokenRegex = /\{([^\}]+)\}/g,
4527 objNotationRegex = /(?:(?:^|\.)(.+?)(?=\[|\.|$|\()|\[('|")(.+?)\2\])(\(\))?/g, // matches .xxxxx or ["xxxxx"] to run over object properties
4528 replacer = function (all, key, obj) {
4530 key.replace(objNotationRegex, function (all, name, quote, quotedName, isFunc) {
4531 name = name || quotedName;
4536 typeof res == "function" && isFunc && (res = res());
4539 res = (res == null || res == obj ? all : res) + "";
4542 return function (str, obj) {
4543 return String(str).replace(tokenRegex, function (all, key) {
4544 return replacer(all, key, obj);
4552 * 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.
4553 * Beware, that in this case plugins could stop working, because they are depending on global variable existance.
4555 = (object) Raphael object
4557 | (function (local_raphael) {
4558 | var paper = local_raphael(10, 10, 320, 200);
4560 | })(Raphael.ninja());
4562 R.ninja = function () {
4563 oldRaphael.was ? (g.win.Raphael = oldRaphael.is) : delete Raphael;
4568 [ property (object) ]
4570 * You can add your own method to elements and sets. It is wise to add a set method for each element method
4571 * you added, so you will be able to call the same method on sets too.
4573 * See also @Raphael.el.
4575 | Raphael.el.red = function () {
4576 | this.attr({fill: "#f00"});
4578 | Raphael.st.red = function () {
4579 | this.forEach(function () {
4584 | paper.set(paper.circle(100, 100, 20), paper.circle(110, 100, 20)).red();
4587 // Firefox <3.6 fix: http://webreflection.blogspot.com/2009/11/195-chars-to-help-lazy-loading.html
4588 (function (doc, loaded, f) {
4589 if (doc.readyState == null && doc.addEventListener){
4590 doc.addEventListener(loaded, f = function () {
4591 doc.removeEventListener(loaded, f, false);
4592 doc.readyState = "complete";
4594 doc.readyState = "loading";
4596 function isLoaded() {
4597 (/in/).test(doc.readyState) ? setTimeout(isLoaded, 9) : R.eve("DOMload");
4600 })(document, "DOMContentLoaded");
4602 oldRaphael.was ? (g.win.Raphael = R) : (Raphael = R);
4604 eve.on("DOMload", function () {