1 // ┌─────────────────────────────────────────────────────────────────────┐ \\
2 // │ "Raphaël 2.0" - JavaScript Vector Library │ \\
3 // ├─────────────────────────────────────────────────────────────────────┤ \\
4 // │ Copyright (c) 2008-2011 Dmitry Baranovskiy (http://raphaeljs.com) │ \\
5 // │ Copyright (c) 2008-2011 Sencha Labs (http://sencha.com) │ \\
6 // │ Licensed under the MIT (http://raphaeljs.com/license.html) license. │ \\
7 // └─────────────────────────────────────────────────────────────────────┘ \\
13 * Creates a canvas object on which to draw.
14 * You must do this first, as all future calls to drawing methods
15 * from this instance will be bound to this canvas.
18 - container (HTMLElement|string) DOM element or its ID which is going to be a parent for drawing surface
21 - callback (function) #optional callback function which is going to be executed in the context of newly created paper
27 - callback (function) #optional callback function which is going to be executed in the context of newly created paper
29 - all (array) (first 3 or 4 elements in the array are equal to [containerID, width, height] or [x, y, width, height]. The rest are element descriptions in format {type: type, <attributes>})
30 - callback (function) #optional callback function which is going to be executed in the context of newly created paper
32 - onReadyCallback (function) function that is going to be called on DOM ready event. You can also subscribe to this event via Eve’s “DOMLoad” event. In this case method returns `undefined`.
35 | // Each of the following examples create a canvas
36 | // that is 320px wide by 200px high.
37 | // Canvas is created at the viewport’s 10,50 coordinate.
38 | var paper = Raphael(10, 50, 320, 200);
39 | // Canvas is created at the top left corner of the #notepad element
40 | // (or its top right corner in dir="rtl" elements)
41 | var paper = Raphael(document.getElementById("notepad"), 320, 200);
43 | var paper = Raphael("notepad", 320, 200);
45 | var set = Raphael(["notepad", 320, 200, {
60 if (R.is(first, "function")) {
61 return loaded ? first() : eve.on("DOMload", first);
62 } else if (R.is(first, array)) {
64 cnv = R._engine.create[apply](R, a.splice(0, 3 + R.is(a[0], nu))),
71 elements[has](j.type) && res.push(cnv[j.type]().attr(j));
75 var args = Array.prototype.slice.call(arguments, 0);
76 if (R.is(args[args.length - 1], "function")) {
78 return loaded ? f.call(R._engine.create[apply](R, args)) : eve.on("DOMload", function () {
79 f.call(R._engine.create[apply](R, args));
82 return R._engine.create[apply](R, arguments);
90 elements = {circle: 1, rect: 1, path: 1, ellipse: 1, text: 1, image: 1},
91 formatrg = /\{(\d+)\}/g,
93 has = "hasOwnProperty",
99 was: Object.prototype[has].call(g.win, "Raphael"),
102 Paper = function () {},
104 appendChild = "appendChild",
107 supportsTouch = "createTouch" in g.doc,
112 events = "click dblclick mousedown mousemove mouseout mouseover mouseup touchstart touchmove touchend orientationchange touchcancel gesturestart gesturechange gestureend".split(S),
114 mousedown: "touchstart",
115 mousemove: "touchmove",
118 lowerCase = Str.prototype.toLowerCase,
128 toString = "toString",
130 objectToString = Object.prototype.toString,
133 ISURL = R._ISURL = /^url\(['"]?([^\)]+?)['"]?\)$/i,
134 colourRegExp = /^\s*((#[a-f\d]{6})|(#[a-f\d]{3})|rgba?\(\s*([\d\.]+%?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\)|hsba?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\)|hsla?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\))\s*$/i,
135 isnan = {"NaN": 1, "Infinity": 1, "-Infinity": 1},
136 bezierrg = /^(?:cubic-)?bezier\(([^,]+),([^,]+),([^,]+),([^\)]+)\)/,
138 setAttribute = "setAttribute",
139 toFloat = parseFloat,
141 ms = " progid:DXImageTransform.Microsoft",
142 upperCase = Str.prototype.toUpperCase,
143 availableAttrs = R._availableAttrs = {
145 "arrow-start": "none",
147 "clip-rect": "0 0 1e9 1e9",
153 font: '10px "Arial"',
154 "font-family": '"Arial"',
156 "font-style": "normal",
160 href: "http://raphaeljs.com/",
168 "stroke-dasharray": "",
169 "stroke-linecap": "butt",
170 "stroke-linejoin": "butt",
171 "stroke-miterlimit": 0,
175 "text-anchor": "middle",
182 availableAnimAttrs = R._availableAnimAttrs = {
197 "stroke-opacity": nu,
199 transform: "transform",
204 commaSpaces = /\s*,\s*/,
205 hsrg = {hs: 1, rg: 1},
206 p2s = /,?([achlmqrstvxz]),?/gi,
207 pathCommand = /([achlmqstvz])[\s,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?\s*,?\s*)+)/ig,
208 tCommand = /([rstm])[\s,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?\s*,?\s*)+)/ig,
209 pathValues = /(-?\d*\.?\d*(?:e[\-+]?\d+)?)\s*,?\s*/ig,
210 radial_gradient = R._radial_gradient = /^r(?:\(([^,]+?)\s*,\s*([^\)]+?)\))?/,
212 sortByKey = function (a, b) {
213 return a.key - b.key;
215 sortByNumber = function (a, b) {
218 fun = function () {},
219 pipe = function (x) {
222 rectPath = R._rectPath = function (x, y, w, h, r) {
224 return [["M", x + r, y], ["l", w - r * 2, 0], ["a", r, r, 0, 0, 1, r, r], ["l", 0, h - r * 2], ["a", r, r, 0, 0, 1, -r, r], ["l", r * 2 - w, 0], ["a", r, r, 0, 0, 1, -r, -r], ["l", 0, r * 2 - h], ["a", r, r, 0, 0, 1, r, -r], ["z"]];
226 return [["M", x, y], ["l", w, 0], ["l", 0, h], ["l", -w, 0], ["z"]];
228 ellipsePath = function (x, y, rx, ry) {
232 return [["M", x, y], ["m", 0, -ry], ["a", rx, ry, 0, 1, 1, 0, 2 * ry], ["a", rx, ry, 0, 1, 1, 0, -2 * ry], ["z"]];
234 getPath = R._getPath = {
235 path: function (el) {
236 return el.attr("path");
238 circle: function (el) {
240 return ellipsePath(a.cx, a.cy, a.r);
242 ellipse: function (el) {
244 return ellipsePath(a.cx, a.cy, a.rx, a.ry);
246 rect: function (el) {
248 return rectPath(a.x, a.y, a.width, a.height, a.r);
250 image: function (el) {
252 return rectPath(a.x, a.y, a.width, a.height);
254 text: function (el) {
255 var bbox = el._getBBox();
256 return rectPath(bbox.x, bbox.y, bbox.width, bbox.height);
259 mapPath = function (path, matrix) {
263 var x, y, i, j, pathi;
264 path = path2curve(path);
265 for (i = 0, ii = path.length; i < ii; i++) {
267 for (j = 1, jj = pathi.length; j < jj; j += 2) {
268 x = matrix.x(pathi[j], pathi[j + 1]);
269 y = matrix.y(pathi[j], pathi[j + 1]);
280 [ property (string) ]
282 * Can be “SVG”, “VML” or empty, depending on browser support.
284 R.type = (g.win.SVGAngle || g.doc.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") ? "SVG" : "VML");
285 if (R.type == "VML") {
286 var d = g.doc.createElement("div"),
288 d.innerHTML = '<v:shape adj="1"/>';
290 b.style.behavior = "url(#default#VML)";
291 if (!(b && typeof b.adj == "object")) {
298 [ property (boolean) ]
300 * `true` if browser supports SVG.
304 [ property (boolean) ]
306 * `true` if browser supports VML.
308 R.svg = !(R.vml = R.type == "VML");
312 [ property (object) ]
314 * You can add your own method to the canvas. For example if you want to draw a pie chart,
315 * you can create your own pie chart function and ship it as a Raphaël plugin. To do this
316 * you need to extend the `Raphael.fn` object. Please note that you can create your own namespaces
317 * inside the `fn` object — methods will be run in the context of canvas anyway. You should alter
318 * the `fn` object before a Raphaël instance is created, otherwise it will take no effect.
320 | Raphael.fn.arrow = function (x1, y1, x2, y2, size) {
321 | return this.path( ... );
323 | // or create namespace
324 | Raphael.fn.mystuff = {
325 | arrow: function () {…},
326 | star: function () {…},
329 | var paper = Raphael(10, 10, 630, 480);
331 | paper.arrow(10, 10, 30, 30, 5).attr({fill: "#f00"});
332 | paper.mystuff.arrow();
333 | paper.mystuff.star();
335 R.fn = paperproto = Paper.prototype = R.prototype;
337 * Paper.customAttributes
338 [ property (object) ]
340 * If you have a set of attributes that you would like to represent
341 * as a function of some number you can do it easily with custom attributes:
343 | paper.customAttributes.hue = function (num) {
345 | return {fill: "hsb(" + num + ", .75, 1)"};
347 | // Custom attribute “hue” will change fill
348 | // to be given hue with fixed saturation and brightness.
349 | // Now you can use it like this:
350 | var c = paper.circle(10, 10, 10).attr({hue: .45});
351 | // or even like this:
352 | c.animate({hue: 1}, 1e3);
354 | // You could also create custom attribute
355 | // with multiple parameters:
356 | paper.customAttributes.hsb = function (h, s, b) {
357 | return {fill: "hsb(" + [h, s, b].join(",") + ")"};
359 | c.attr({hsb: ".5 .8 1"});
360 | c.animate({hsb: "1 0 .5"}, 1e3);
362 paperproto.customAttributes = {};
369 * Handfull replacement for `typeof` operator.
371 - o (…) any object or primitive
372 - type (string) name of the type, i.e. “string”, “function”, “number”, etc.
373 = (boolean) is given value is of given type
375 R.is = function (o, type) {
376 type = lowerCase.call(type);
377 if (type == "finite") {
378 return !isnan[has](+o);
380 if (type == "array") {
381 return o instanceof Array;
383 return (type == "null" && o === null) ||
384 (type == typeof o) ||
385 (type == "object" && o === Object(o)) ||
386 (type == "array" && Array.isArray && Array.isArray(o)) ||
387 objectToString.call(o).slice(8, -1).toLowerCase() == type;
393 * Returns angle between two or three points
395 - x1 (number) x coord of first point
396 - y1 (number) y coord of first point
397 - x2 (number) x coord of second point
398 - y2 (number) y coord of second point
399 - x3 (number) #optional x coord of third point
400 - y3 (number) #optional y coord of third point
401 = (number) angle in degrees.
403 R.angle = function (x1, y1, x2, y2, x3, y3) {
410 return (180 + math.atan2(-y, -x) * 180 / PI + 360) % 360;
412 return R.angle(x1, y1, x3, y3) - R.angle(x2, y2, x3, y3);
419 * Transform angle to radians
421 - deg (number) angle in degrees
422 = (number) angle in radians.
424 R.rad = function (deg) {
425 return deg % 360 * PI / 180;
431 * Transform angle to degrees
433 - deg (number) angle in radians
434 = (number) angle in degrees.
436 R.deg = function (rad) {
437 return rad * 180 / PI % 360;
443 * Snaps given value to given grid.
445 - values (array|number) given array of values or step of the grid
446 - value (number) value to adjust
447 - tolerance (number) #optional tolerance for snapping. Default is `10`.
448 = (number) adjusted value.
450 R.snapTo = function (values, value, tolerance) {
451 tolerance = R.is(tolerance, "finite") ? tolerance : 10;
452 if (R.is(values, array)) {
453 var i = values.length;
454 while (i--) if (abs(values[i] - value) <= tolerance) {
459 var rem = value % values;
460 if (rem < tolerance) {
463 if (rem > values - tolerance) {
464 return value - rem + values;
470 var createUUID = R._createUUID = (function (uuidRegEx, uuidReplacer) {
472 return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(uuidRegEx, uuidReplacer).toUpperCase();
474 })(/[xy]/g, function (c) {
475 var r = math.random() * 16 | 0,
476 v = c == "x" ? r : (r & 3 | 8);
477 return v.toString(16);
484 * Used when you need to draw in `<iframe>`. Switched window to the iframe one.
486 - newwin (window) new window object
488 R.setWindow = function (newwin) {
489 eve("setWindow", R, g.win, newwin);
491 g.doc = g.win.document;
497 var toHex = function (color) {
499 // http://dean.edwards.name/weblog/2009/10/convert-any-colour-value-to-hex-in-msie/
500 var trim = /^\s+|\s+$/g;
503 var docum = new ActiveXObject("htmlfile");
504 docum.write("<body>");
508 bod = createPopup().document.body;
510 var range = bod.createTextRange();
511 toHex = cacher(function (color) {
513 bod.style.color = Str(color).replace(trim, E);
514 var value = range.queryCommandValue("ForeColor");
515 value = ((value & 255) << 16) | (value & 65280) | ((value & 16711680) >>> 16);
516 return "#" + ("000000" + value.toString(16)).slice(-6);
522 var i = g.doc.createElement("i");
523 i.title = "Rapha\xebl Colour Picker";
524 i.style.display = "none";
525 g.doc.body.appendChild(i);
526 toHex = cacher(function (color) {
527 i.style.color = color;
528 return g.doc.defaultView.getComputedStyle(i, E).getPropertyValue("color");
533 hsbtoString = function () {
534 return "hsb(" + [this.h, this.s, this.b] + ")";
536 hsltoString = function () {
537 return "hsl(" + [this.h, this.s, this.l] + ")";
539 rgbtoString = function () {
542 prepareRGB = function (r, g, b) {
543 if (g == null && R.is(r, "object") && "r" in r && "g" in r && "b" in r) {
548 if (g == null && R.is(r, string)) {
549 var clr = R.getRGB(r);
554 if (r > 1 || g > 1 || b > 1) {
562 packageRGB = function (r, g, b, o) {
571 toString: rgbtoString
573 R.is(o, "finite") && (rgb.opacity = o);
581 * Parses the color string and returns object with all values for the given color.
583 - clr (string) color string in one of the supported formats (see @Raphael.getRGB)
584 = (object) Combined RGB & HSB object in format:
589 o hex (string) color in HTML/CSS format: #••••••,
590 o error (boolean) `true` if string can’t be parsed,
592 o s (number) saturation,
593 o v (number) value (brightness),
594 o l (number) lightness
597 R.color = function (clr) {
599 if (R.is(clr, "object") && "h" in clr && "s" in clr && "b" in clr) {
600 rgb = R.hsb2rgb(clr);
605 } else if (R.is(clr, "object") && "h" in clr && "s" in clr && "l" in clr) {
606 rgb = R.hsl2rgb(clr);
612 if (R.is(clr, "string")) {
615 if (R.is(clr, "object") && "r" in clr && "g" in clr && "b" in clr) {
616 rgb = R.rgb2hsl(clr);
620 rgb = R.rgb2hsb(clr);
624 crl.r = clr.g = clr.b = clr.h = clr.s = clr.v = clr.l = -1;
627 clr.toString = rgbtoString;
634 * Converts HSB values to RGB object.
637 - s (number) saturation
638 - v (number) value or brightness
639 = (object) RGB object in format:
644 o hex (string) color in HTML/CSS format: #••••••
647 R.hsb2rgb = function (h, s, v, o) {
648 if (this.is(h, "object") && "h" in h && "s" in h && "b" in h) {
658 X = C * (1 - abs(h % 2 - 1));
662 R += [C, X, 0, 0, X, C][h];
663 G += [X, C, C, X, 0, 0][h];
664 B += [0, 0, X, C, C, X][h];
665 return packageRGB(R, G, B, o);
671 * Converts HSL values to RGB object.
674 - s (number) saturation
675 - l (number) luminosity
676 = (object) RGB object in format:
681 o hex (string) color in HTML/CSS format: #••••••
684 R.hsl2rgb = function (h, s, l, o) {
685 if (this.is(h, "object") && "h" in h && "s" in h && "l" in h) {
690 if (h > 1 || s > 1 || l > 1) {
698 C = 2 * s * (l < .5 ? l : 1 - l);
699 X = C * (1 - abs(h % 2 - 1));
700 R = G = B = l - C / 2;
703 R += [C, X, 0, 0, X, C][h];
704 G += [X, C, C, X, 0, 0][h];
705 B += [0, 0, X, C, C, X][h];
706 return packageRGB(R, G, B, o);
712 * Converts RGB values to HSB object.
717 = (object) HSB object in format:
720 o s (number) saturation
721 o b (number) brightness
724 R.rgb2hsb = function (r, g, b) {
725 b = prepareRGB(r, g, b);
732 C = V - mmin(r, g, b);
734 V == r ? (g - b) / C :
735 V == g ? (b - r) / C + 2 :
738 H = ((H + 360) % 6) * 60 / 360;
739 S = C == 0 ? 0 : C / V;
740 return {h: H, s: S, b: V, toString: hsbtoString};
746 * Converts RGB values to HSL object.
751 = (object) HSL object in format:
754 o s (number) saturation
755 o l (number) luminosity
758 R.rgb2hsl = function (r, g, b) {
759 b = prepareRGB(r, g, b);
764 var H, S, L, M, m, C;
769 M == r ? (g - b) / C :
770 M == g ? (b - r) / C + 2 :
772 H = ((H + 360) % 6) * 60 / 360;
775 L < .5 ? C / (2 * L) :
777 return {h: H, s: S, l: L, toString: hsltoString};
779 R._path2string = function () {
780 return this.join(",").replace(p2s, "$1");
782 function repush(array, item) {
783 for (var i = 0, ii = array.length; i < ii; i++) if (array[i] === item) {
784 return array.push(array.splice(i, 1)[0]);
787 function cacher(f, scope, postprocessor) {
789 var arg = Array.prototype.slice.call(arguments, 0),
790 args = arg.join("\u2400"),
791 cache = newf.cache = newf.cache || {},
792 count = newf.count = newf.count || [];
793 if (cache[has](args)) {
795 return postprocessor ? postprocessor(cache[args]) : cache[args];
797 count.length >= 1e3 && delete cache[count.shift()];
799 cache[args] = f[apply](scope, arg);
800 return postprocessor ? postprocessor(cache[args]) : cache[args];
805 var preload = R._preload = function (src, f) {
806 var img = g.doc.createElement("img");
807 img.style.cssText = "position:absolute;left:-9999em;top-9999em";
808 img.onload = function () {
811 g.doc.body.removeChild(this);
813 img.onerror = function () {
814 g.doc.body.removeChild(this);
816 g.doc.body.appendChild(img);
820 function clrToString() {
828 * Parses colour string as RGB object
830 - colour (string) colour string in one of formats:
832 # <li>Colour name (“<code>red</code>”, “<code>green</code>”, “<code>cornflowerblue</code>”, etc)</li>
833 # <li>#••• — shortened HTML colour: (“<code>#000</code>”, “<code>#fc0</code>”, etc)</li>
834 # <li>#•••••• — full length HTML colour: (“<code>#000000</code>”, “<code>#bd2300</code>”)</li>
835 # <li>rgb(•••, •••, •••) — red, green and blue channels’ values: (“<code>rgb(200, 100, 0)</code>”)</li>
836 # <li>rgb(•••%, •••%, •••%) — same as above, but in %: (“<code>rgb(100%, 175%, 0%)</code>”)</li>
837 # <li>hsb(•••, •••, •••) — hue, saturation and brightness values: (“<code>hsb(0.5, 0.25, 1)</code>”)</li>
838 # <li>hsb(•••%, •••%, •••%) — same as above, but in %</li>
839 # <li>hsl(•••, •••, •••) — same as hsb</li>
840 # <li>hsl(•••%, •••%, •••%) — same as hsb</li>
842 = (object) RGB object in format:
847 o hex (string) color in HTML/CSS format: #••••••,
848 o error (boolean) true if string can’t be parsed
851 R.getRGB = cacher(function (colour) {
852 if (!colour || !!((colour = Str(colour)).indexOf("-") + 1)) {
853 return {r: -1, g: -1, b: -1, hex: "none", error: 1, toString: clrToString};
855 if (colour == "none") {
856 return {r: -1, g: -1, b: -1, hex: "none", toString: clrToString};
858 !(hsrg[has](colour.toLowerCase().substring(0, 2)) || colour.charAt() == "#") && (colour = toHex(colour));
866 rgb = colour.match(colourRegExp);
869 blue = toInt(rgb[2].substring(5), 16);
870 green = toInt(rgb[2].substring(3, 5), 16);
871 red = toInt(rgb[2].substring(1, 3), 16);
874 blue = toInt((t = rgb[3].charAt(3)) + t, 16);
875 green = toInt((t = rgb[3].charAt(2)) + t, 16);
876 red = toInt((t = rgb[3].charAt(1)) + t, 16);
879 values = rgb[4].split(commaSpaces);
880 red = toFloat(values[0]);
881 values[0].slice(-1) == "%" && (red *= 2.55);
882 green = toFloat(values[1]);
883 values[1].slice(-1) == "%" && (green *= 2.55);
884 blue = toFloat(values[2]);
885 values[2].slice(-1) == "%" && (blue *= 2.55);
886 rgb[1].toLowerCase().slice(0, 4) == "rgba" && (opacity = toFloat(values[3]));
887 values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
890 values = rgb[5].split(commaSpaces);
891 red = toFloat(values[0]);
892 values[0].slice(-1) == "%" && (red *= 2.55);
893 green = toFloat(values[1]);
894 values[1].slice(-1) == "%" && (green *= 2.55);
895 blue = toFloat(values[2]);
896 values[2].slice(-1) == "%" && (blue *= 2.55);
897 (values[0].slice(-3) == "deg" || values[0].slice(-1) == "\xb0") && (red /= 360);
898 rgb[1].toLowerCase().slice(0, 4) == "hsba" && (opacity = toFloat(values[3]));
899 values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
900 return R.hsb2rgb(red, green, blue, opacity);
903 values = rgb[6].split(commaSpaces);
904 red = toFloat(values[0]);
905 values[0].slice(-1) == "%" && (red *= 2.55);
906 green = toFloat(values[1]);
907 values[1].slice(-1) == "%" && (green *= 2.55);
908 blue = toFloat(values[2]);
909 values[2].slice(-1) == "%" && (blue *= 2.55);
910 (values[0].slice(-3) == "deg" || values[0].slice(-1) == "\xb0") && (red /= 360);
911 rgb[1].toLowerCase().slice(0, 4) == "hsla" && (opacity = toFloat(values[3]));
912 values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
913 return R.hsl2rgb(red, green, blue, opacity);
915 rgb = {r: red, g: green, b: blue, toString: clrToString};
916 rgb.hex = "#" + (16777216 | blue | (green << 8) | (red << 16)).toString(16).slice(1);
917 R.is(opacity, "finite") && (rgb.opacity = opacity);
920 return {r: -1, g: -1, b: -1, hex: "none", error: 1, toString: clrToString};
926 * Converts HSB values to hex representation of the colour.
929 - s (number) saturation
930 - b (number) value or brightness
931 = (string) hex representation of the colour.
933 R.hsb = cacher(function (h, s, b) {
934 return R.hsb2rgb(h, s, b).hex;
940 * Converts HSL values to hex representation of the colour.
943 - s (number) saturation
944 - l (number) luminosity
945 = (string) hex representation of the colour.
947 R.hsl = cacher(function (h, s, l) {
948 return R.hsl2rgb(h, s, l).hex;
954 * Converts RGB values to hex representation of the colour.
959 = (string) hex representation of the colour.
961 R.rgb = cacher(function (r, g, b) {
962 return "#" + (16777216 | b | (g << 8) | (r << 16)).toString(16).slice(1);
968 * On each call returns next colour in the spectrum. To reset it back to red call @Raphael.getColor.reset
970 - value (number) #optional brightness, default is `0.75`
971 = (string) hex representation of the colour.
973 R.getColor = function (value) {
974 var start = this.getColor.start = this.getColor.start || {h: 0, s: 1, b: value || .75},
975 rgb = this.hsb2rgb(start.h, start.s, start.b);
980 start.s <= 0 && (this.getColor.start = {h: 0, s: 1, b: start.b});
985 * Raphael.getColor.reset
988 * Resets spectrum position for @Raphael.getColor back to red.
990 R.getColor.reset = function () {
995 * Raphael.parsePathString
1000 * Parses given path string into an array of arrays of path segments.
1002 - pathString (string|array) path string or array of segments (in the last case it will be returned straight away)
1003 = (array) array of segments.
1005 R.parsePathString = cacher(function (pathString) {
1009 var paramCounts = {a: 7, c: 6, h: 1, l: 2, m: 2, q: 4, s: 4, t: 2, v: 1, z: 0},
1011 if (R.is(pathString, array) && R.is(pathString[0], array)) { // rough assumption
1012 data = pathClone(pathString);
1015 Str(pathString).replace(pathCommand, function (a, b, c) {
1017 name = lowerCase.call(b);
1018 c.replace(pathValues, function (a, b) {
1019 b && params.push(+b);
1021 if (name == "m" && params.length > 2) {
1022 data.push([b][concat](params.splice(0, 2)));
1024 b = b == "m" ? "l" : "L";
1026 while (params.length >= paramCounts[name]) {
1027 data.push([b][concat](params.splice(0, paramCounts[name])));
1028 if (!paramCounts[name]) {
1034 data.toString = R._path2string;
1038 * Raphael.parseTransformString
1043 * Parses given path string into an array of transformations.
1045 - TString (string|array) transform string or array of transformations (in the last case it will be returned straight away)
1046 = (array) array of transformations.
1048 R.parseTransformString = cacher(function (TString) {
1052 var paramCounts = {r: 3, s: 4, t: 2, m: 6},
1054 if (R.is(TString, array) && R.is(TString[0], array)) { // rough assumption
1055 data = pathClone(TString);
1058 Str(TString).replace(tCommand, function (a, b, c) {
1060 name = lowerCase.call(b);
1061 c.replace(pathValues, function (a, b) {
1062 b && params.push(+b);
1064 data.push([name][concat](params));
1067 data.toString = R._path2string;
1071 * Raphael.findDotsAtSegment
1076 * Find dot coordinates on the given cubic bezier curve at the given t.
1078 - p1x (number) x of the first point of the curve
1079 - p1y (number) y of the first point of the curve
1080 - c1x (number) x of the first anchor of the curve
1081 - c1y (number) y of the first anchor of the curve
1082 - c2x (number) x of the second anchor of the curve
1083 - c2y (number) y of the second anchor of the curve
1084 - p2x (number) x of the second point of the curve
1085 - p2y (number) y of the second point of the curve
1086 - t (number) position on the curve (0..1)
1087 = (object) point information in format:
1089 o x: (number) x coordinate of the point
1090 o y: (number) y coordinate of the point
1092 o x: (number) x coordinate of the left anchor
1093 o y: (number) y coordinate of the left anchor
1096 o x: (number) x coordinate of the right anchor
1097 o y: (number) y coordinate of the right anchor
1100 o x: (number) x coordinate of the start of the curve
1101 o y: (number) y coordinate of the start of the curve
1104 o x: (number) x coordinate of the end of the curve
1105 o y: (number) y coordinate of the end of the curve
1107 o alpha: (number) angle of the curve derivative at the point
1110 R.findDotsAtSegment = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) {
1112 x = pow(t1, 3) * p1x + pow(t1, 2) * 3 * t * c1x + t1 * 3 * t * t * c2x + pow(t, 3) * p2x,
1113 y = pow(t1, 3) * p1y + pow(t1, 2) * 3 * t * c1y + t1 * 3 * t * t * c2y + pow(t, 3) * p2y,
1114 mx = p1x + 2 * t * (c1x - p1x) + t * t * (c2x - 2 * c1x + p1x),
1115 my = p1y + 2 * t * (c1y - p1y) + t * t * (c2y - 2 * c1y + p1y),
1116 nx = c1x + 2 * t * (c2x - c1x) + t * t * (p2x - 2 * c2x + c1x),
1117 ny = c1y + 2 * t * (c2y - c1y) + t * t * (p2y - 2 * c2y + c1y),
1118 ax = (1 - t) * p1x + t * c1x,
1119 ay = (1 - t) * p1y + t * c1y,
1120 cx = (1 - t) * c2x + t * p2x,
1121 cy = (1 - t) * c2y + t * p2y,
1122 alpha = (90 - math.atan2(mx - nx, my - ny) * 180 / PI);
1123 (mx > nx || my < ny) && (alpha += 180);
1129 start: {x: ax, y: ay},
1130 end: {x: cx, y: cy},
1134 var pathDimensions = cacher(function (path) {
1136 return {x: 0, y: 0, width: 0, height: 0};
1138 path = path2curve(path);
1144 for (var i = 0, ii = path.length; i < ii; i++) {
1152 var dim = curveDim(x, y, p[1], p[2], p[3], p[4], p[5], p[6]);
1153 X = X[concat](dim.min.x, dim.max.x);
1154 Y = Y[concat](dim.min.y, dim.max.y);
1159 var xmin = mmin[apply](0, X),
1160 ymin = mmin[apply](0, Y);
1164 width: mmax[apply](0, X) - xmin,
1165 height: mmax[apply](0, Y) - ymin
1167 }, null, function (o) {
1175 pathClone = function (pathArray) {
1177 if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) { // rough assumption
1178 pathArray = R.parsePathString(pathArray);
1180 for (var i = 0, ii = pathArray.length; i < ii; i++) {
1182 for (var j = 0, jj = pathArray[i].length; j < jj; j++) {
1183 res[i][j] = pathArray[i][j];
1186 res.toString = R._path2string;
1189 pathToRelative = R._pathToRelative = cacher(function (pathArray) {
1190 if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) { // rough assumption
1191 pathArray = R.parsePathString(pathArray);
1199 if (pathArray[0][0] == "M") {
1200 x = pathArray[0][1];
1201 y = pathArray[0][2];
1205 res.push(["M", x, y]);
1207 for (var i = start, ii = pathArray.length; i < ii; i++) {
1208 var r = res[i] = [],
1210 if (pa[0] != lowerCase.call(pa[0])) {
1211 r[0] = lowerCase.call(pa[0]);
1219 r[6] = +(pa[6] - x).toFixed(3);
1220 r[7] = +(pa[7] - y).toFixed(3);
1223 r[1] = +(pa[1] - y).toFixed(3);
1229 for (var j = 1, jj = pa.length; j < jj; j++) {
1230 r[j] = +(pa[j] - ((j % 2) ? x : y)).toFixed(3);
1239 for (var k = 0, kk = pa.length; k < kk; k++) {
1243 var len = res[i].length;
1244 switch (res[i][0]) {
1250 x += +res[i][len - 1];
1253 y += +res[i][len - 1];
1256 x += +res[i][len - 2];
1257 y += +res[i][len - 1];
1260 res.toString = R._path2string;
1263 pathToAbsolute = R._pathToAbsolute = cacher(function (pathArray) {
1264 if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) { // rough assumption
1265 pathArray = R.parsePathString(pathArray);
1267 if (!pathArray || !pathArray.length) {
1268 return [["M", 0, 0]];
1276 if (pathArray[0][0] == "M") {
1277 x = +pathArray[0][1];
1278 y = +pathArray[0][2];
1282 res[0] = ["M", x, y];
1284 for (var i = start, ii = pathArray.length; i < ii; i++) {
1285 var r = res[i] = [],
1287 if (pa[0] != upperCase.call(pa[0])) {
1288 r[0] = upperCase.call(pa[0]);
1296 r[6] = +(pa[6] + x);
1297 r[7] = +(pa[7] + y);
1309 for (var j = 1, jj = pa.length; j < jj; j++) {
1310 r[j] = +pa[j] + ((j % 2) ? x : y);
1314 for (var k = 0, kk = pa.length; k < kk; k++) {
1330 mx = res[i][res[i].length - 2];
1331 my = res[i][res[i].length - 1];
1333 x = res[i][res[i].length - 2];
1334 y = res[i][res[i].length - 1];
1337 res.toString = R._path2string;
1339 }, null, pathClone),
1340 l2c = function (x1, y1, x2, y2) {
1341 return [x1, y1, x2, y2, x2, y2];
1343 q2c = function (x1, y1, ax, ay, x2, y2) {
1347 _13 * x1 + _23 * ax,
1348 _13 * y1 + _23 * ay,
1349 _13 * x2 + _23 * ax,
1350 _13 * y2 + _23 * ay,
1355 a2c = function (x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursive) {
1356 // for more information of where this math came from visit:
1357 // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
1358 var _120 = PI * 120 / 180,
1359 rad = PI / 180 * (+angle || 0),
1362 rotate = cacher(function (x, y, rad) {
1363 var X = x * math.cos(rad) - y * math.sin(rad),
1364 Y = x * math.sin(rad) + y * math.cos(rad);
1365 return {x: X, y: Y};
1368 xy = rotate(x1, y1, -rad);
1371 xy = rotate(x2, y2, -rad);
1374 var cos = math.cos(PI / 180 * angle),
1375 sin = math.sin(PI / 180 * angle),
1378 var h = (x * x) / (rx * rx) + (y * y) / (ry * ry);
1386 k = (large_arc_flag == sweep_flag ? -1 : 1) *
1387 math.sqrt(abs((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x))),
1388 cx = k * rx * y / ry + (x1 + x2) / 2,
1389 cy = k * -ry * x / rx + (y1 + y2) / 2,
1390 f1 = math.asin(((y1 - cy) / ry).toFixed(9)),
1391 f2 = math.asin(((y2 - cy) / ry).toFixed(9));
1393 f1 = x1 < cx ? PI - f1 : f1;
1394 f2 = x2 < cx ? PI - f2 : f2;
1395 f1 < 0 && (f1 = PI * 2 + f1);
1396 f2 < 0 && (f2 = PI * 2 + f2);
1397 if (sweep_flag && f1 > f2) {
1400 if (!sweep_flag && f2 > f1) {
1410 if (abs(df) > _120) {
1414 f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1);
1415 x2 = cx + rx * math.cos(f2);
1416 y2 = cy + ry * math.sin(f2);
1417 res = a2c(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [f2, f2old, cx, cy]);
1420 var c1 = math.cos(f1),
1424 t = math.tan(df / 4),
1425 hx = 4 / 3 * rx * t,
1426 hy = 4 / 3 * ry * t,
1428 m2 = [x1 + hx * s1, y1 - hy * c1],
1429 m3 = [x2 + hx * s2, y2 - hy * c2],
1431 m2[0] = 2 * m1[0] - m2[0];
1432 m2[1] = 2 * m1[1] - m2[1];
1434 return [m2, m3, m4][concat](res);
1436 res = [m2, m3, m4][concat](res).join().split(",");
1438 for (var i = 0, ii = res.length; i < ii; i++) {
1439 newres[i] = i % 2 ? rotate(res[i - 1], res[i], rad).y : rotate(res[i], res[i + 1], rad).x;
1444 findDotAtSegment = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) {
1447 x: pow(t1, 3) * p1x + pow(t1, 2) * 3 * t * c1x + t1 * 3 * t * t * c2x + pow(t, 3) * p2x,
1448 y: pow(t1, 3) * p1y + pow(t1, 2) * 3 * t * c1y + t1 * 3 * t * t * c2y + pow(t, 3) * p2y
1451 curveDim = cacher(function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) {
1452 var a = (c2x - 2 * c1x + p1x) - (p2x - 2 * c2x + c1x),
1453 b = 2 * (c1x - p1x) - 2 * (c2x - c1x),
1455 t1 = (-b + math.sqrt(b * b - 4 * a * c)) / 2 / a,
1456 t2 = (-b - math.sqrt(b * b - 4 * a * c)) / 2 / a,
1460 abs(t1) > "1e12" && (t1 = .5);
1461 abs(t2) > "1e12" && (t2 = .5);
1462 if (t1 > 0 && t1 < 1) {
1463 dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t1);
1467 if (t2 > 0 && t2 < 1) {
1468 dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t2);
1472 a = (c2y - 2 * c1y + p1y) - (p2y - 2 * c2y + c1y);
1473 b = 2 * (c1y - p1y) - 2 * (c2y - c1y);
1475 t1 = (-b + math.sqrt(b * b - 4 * a * c)) / 2 / a;
1476 t2 = (-b - math.sqrt(b * b - 4 * a * c)) / 2 / a;
1477 abs(t1) > "1e12" && (t1 = .5);
1478 abs(t2) > "1e12" && (t2 = .5);
1479 if (t1 > 0 && t1 < 1) {
1480 dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t1);
1484 if (t2 > 0 && t2 < 1) {
1485 dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t2);
1490 min: {x: mmin[apply](0, x), y: mmin[apply](0, y)},
1491 max: {x: mmax[apply](0, x), y: mmax[apply](0, y)}
1494 path2curve = cacher(function (path, path2) {
1495 var p = pathToAbsolute(path),
1496 p2 = path2 && pathToAbsolute(path2),
1497 attrs = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null},
1498 attrs2 = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null},
1499 processPath = function (path, d) {
1502 return ["C", d.x, d.y, d.x, d.y, d.x, d.y];
1504 !(path[0] in {T:1, Q:1}) && (d.qx = d.qy = null);
1511 path = ["C"][concat](a2c[apply](0, [d.x, d.y][concat](path.slice(1))));
1514 nx = d.x + (d.x - (d.bx || d.x));
1515 ny = d.y + (d.y - (d.by || d.y));
1516 path = ["C", nx, ny][concat](path.slice(1));
1519 d.qx = d.x + (d.x - (d.qx || d.x));
1520 d.qy = d.y + (d.y - (d.qy || d.y));
1521 path = ["C"][concat](q2c(d.x, d.y, d.qx, d.qy, path[1], path[2]));
1526 path = ["C"][concat](q2c(d.x, d.y, path[1], path[2], path[3], path[4]));
1529 path = ["C"][concat](l2c(d.x, d.y, path[1], path[2]));
1532 path = ["C"][concat](l2c(d.x, d.y, path[1], d.y));
1535 path = ["C"][concat](l2c(d.x, d.y, d.x, path[1]));
1538 path = ["C"][concat](l2c(d.x, d.y, d.X, d.Y));
1543 fixArc = function (pp, i) {
1544 if (pp[i].length > 7) {
1548 pp.splice(i++, 0, ["C"][concat](pi.splice(0, 6)));
1551 ii = mmax(p.length, p2 && p2.length || 0);
1554 fixM = function (path1, path2, a1, a2, i) {
1555 if (path1 && path2 && path1[i][0] == "M" && path2[i][0] != "M") {
1556 path2.splice(i, 0, ["M", a2.x, a2.y]);
1561 ii = mmax(p.length, p2 && p2.length || 0);
1564 for (var i = 0, ii = mmax(p.length, p2 && p2.length || 0); i < ii; i++) {
1565 p[i] = processPath(p[i], attrs);
1567 p2 && (p2[i] = processPath(p2[i], attrs2));
1568 p2 && fixArc(p2, i);
1569 fixM(p, p2, attrs, attrs2, i);
1570 fixM(p2, p, attrs2, attrs, i);
1573 seglen = seg.length,
1574 seg2len = p2 && seg2.length;
1575 attrs.x = seg[seglen - 2];
1576 attrs.y = seg[seglen - 1];
1577 attrs.bx = toFloat(seg[seglen - 4]) || attrs.x;
1578 attrs.by = toFloat(seg[seglen - 3]) || attrs.y;
1579 attrs2.bx = p2 && (toFloat(seg2[seg2len - 4]) || attrs2.x);
1580 attrs2.by = p2 && (toFloat(seg2[seg2len - 3]) || attrs2.y);
1581 attrs2.x = p2 && seg2[seg2len - 2];
1582 attrs2.y = p2 && seg2[seg2len - 1];
1584 return p2 ? [p, p2] : p;
1585 }, null, pathClone),
1586 parseDots = R._parseDots = cacher(function (gradient) {
1588 for (var i = 0, ii = gradient.length; i < ii; i++) {
1590 par = gradient[i].match(/^([^:]*):?([\d\.]*)/);
1591 dot.color = R.getRGB(par[1]);
1592 if (dot.color.error) {
1595 dot.color = dot.color.hex;
1596 par[2] && (dot.offset = par[2] + "%");
1599 for (i = 1, ii = dots.length - 1; i < ii; i++) {
1600 if (!dots[i].offset) {
1601 var start = toFloat(dots[i - 1].offset || 0),
1603 for (var j = i + 1; j < ii; j++) {
1604 if (dots[j].offset) {
1605 end = dots[j].offset;
1614 var d = (end - start) / (j - i + 1);
1615 for (; i < j; i++) {
1617 dots[i].offset = start + "%";
1623 tear = R._tear = function (el, paper) {
1624 el == paper.top && (paper.top = el.prev);
1625 el == paper.bottom && (paper.bottom = el.next);
1626 el.next && (el.next.prev = el.prev);
1627 el.prev && (el.prev.next = el.next);
1629 tofront = R._tofront = function (el, paper) {
1630 if (paper.top === el) {
1635 el.prev = paper.top;
1636 paper.top.next = el;
1639 toback = R._toback = function (el, paper) {
1640 if (paper.bottom === el) {
1644 el.next = paper.bottom;
1646 paper.bottom.prev = el;
1649 insertafter = R._insertafter = function (el, el2, paper) {
1651 el2 == paper.top && (paper.top = el);
1652 el2.next && (el2.next.prev = el);
1657 insertbefore = R._insertbefore = function (el, el2, paper) {
1659 el2 == paper.bottom && (paper.bottom = el);
1660 el2.prev && (el2.prev.next = el);
1665 removed = function (methodname) {
1666 return function () {
1667 throw new Error("Rapha\xebl: you are calling to method \u201c" + methodname + "\u201d of removed object");
1670 extractTransform = R._extractTransform = function (el, tstr) {
1672 return el._.transform;
1674 tstr = Str(tstr).replace(/\.{3}|\u2026/g, el._.transform || E);
1675 var tdata = R.parseTransformString(tstr),
1683 _.transform = tdata || [];
1685 for (var i = 0, ii = tdata.length; i < ii; i++) {
1689 t[0] = Str(t[0]).toLowerCase();
1690 if (t[0] == "t" && tlen == 3) {
1691 m.translate(t[1], t[2]);
1692 } else if (t[0] == "r") {
1694 bb = bb || el.getBBox(1);
1695 m.rotate(t[1], bb.x + bb.width / 2, bb.y + bb.height / 2);
1697 } else if (tlen == 4) {
1698 m.rotate(t[1], t[2], t[3]);
1701 } else if (t[0] == "s") {
1702 if (tlen == 2 || tlen == 3) {
1703 bb = bb || el.getBBox(1);
1704 m.scale(t[1], t[tlen - 1], bb.x + bb.width / 2, bb.y + bb.height / 2);
1707 } else if (tlen == 5) {
1708 m.scale(t[1], t[2], t[3], t[4]);
1712 } else if (t[0] == "m" && tlen == 7) {
1713 m.add(t[1], t[2], t[3], t[4], t[5], t[6]);
1728 if (sx == 1 && sy == 1 && !deg && _.bbox) {
1735 getEmpty = function (item) {
1737 case "t": return ["t", 0, 0];
1738 case "m": return ["m", 1, 0, 0, 1, 0, 0];
1739 case "r": if (item.length == 4) {
1740 return ["r", 0, item[2], item[3]];
1744 case "s": if (item.length == 5) {
1745 return ["s", 1, 1, item[3], item[4]];
1746 } else if (item.length == 3) {
1753 equaliseTransform = R._equaliseTransform = function (t1, t2) {
1754 t2 = Str(t2).replace(/\.{3}|\u2026/g, t1);
1755 t1 = R.parseTransformString(t1) || [];
1756 t2 = R.parseTransformString(t2) || [];
1757 var maxlength = mmax(t1.length, t2.length),
1762 for (; i < maxlength; i++) {
1763 tt1 = t1[i] || getEmpty(t2[i]);
1764 tt2 = t2[i] || getEmpty(tt1);
1765 if ((tt1[0] != tt2[0]) ||
1766 (tt1[0] == "r" && (tt1[2] != tt2[2] || tt1[3] != tt2[3])) ||
1767 (tt1[0] == "s" && (tt1[3] != tt2[3] || tt1[4] != tt2[4]))
1773 for (j = 0, jj = mmax(tt1.length, tt2.length); j < jj; j++) {
1774 j in tt1 && (from[i][j] = tt1[j]);
1775 j in tt2 && (to[i][j] = tt2[j]);
1783 R._getContainer = function (x, y, w, h) {
1785 container = h == null && !R.is(x, "object") ? g.doc.getElementById(x) : x;
1786 if (container == null) {
1789 if (container.tagName) {
1792 container: container,
1793 width: container.style.pixelWidth || container.offsetWidth,
1794 height: container.style.pixelHeight || container.offsetHeight
1798 container: container,
1813 * Raphael.pathToRelative
1818 * Converts path to relative form
1820 - pathString (string|array) path string or array of segments
1821 = (array) array of segments.
1823 R.pathToRelative = pathToRelative;
1826 * Raphael.path2curve
1831 * Converts path to a new path where all segments are cubic bezier curves.
1833 - pathString (string|array) path string or array of segments
1834 = (array) array of segments.
1836 R.path2curve = path2curve;
1843 * Returns matrix based on given parameters.
1853 R.matrix = function (a, b, c, d, e, f) {
1854 return new Matrix(a, b, c, d, e, f);
1856 function Matrix(a, b, c, d, e, f) {
1873 (function (matrixproto) {
1878 * Adds given matrix to existing one.
1887 - matrix (object) @Matrix
1889 matrixproto.add = function (a, b, c, d, e, f) {
1890 var out = [[], [], []],
1891 m = [[this.a, this.c, this.e], [this.b, this.d, this.f], [0, 0, 1]],
1892 matrix = [[a, c, e], [b, d, f], [0, 0, 1]],
1895 if (a && a instanceof Matrix) {
1896 matrix = [[a.a, a.c, a.e], [a.b, a.d, a.f], [0, 0, 1]];
1899 for (x = 0; x < 3; x++) {
1900 for (y = 0; y < 3; y++) {
1902 for (z = 0; z < 3; z++) {
1903 res += m[x][z] * matrix[z][y];
1919 * Returns inverted version of the matrix
1922 matrixproto.invert = function () {
1924 x = me.a * me.d - me.b * me.c;
1925 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);
1931 * Returns copy of the matrix
1934 matrixproto.clone = function () {
1935 return new Matrix(this.a, this.b, this.c, this.d, this.e, this.f);
1941 * Translate the matrix
1946 matrixproto.translate = function (x, y) {
1947 this.add(1, 0, 0, 1, x, y);
1956 - y (number) #optional
1957 - cx (number) #optional
1958 - cy (number) #optional
1960 matrixproto.scale = function (x, y, cx, cy) {
1961 y == null && (y = x);
1962 cx || cy && this.add(1, 0, 0, 1, cx, cy);
1963 this.add(x, 0, 0, y, 0, 0);
1964 cx || cy && this.add(1, 0, 0, 1, -cx, -cy);
1970 * Rotates the matrix
1976 matrixproto.rotate = function (a, x, y) {
1980 var cos = +math.cos(a).toFixed(9),
1981 sin = +math.sin(a).toFixed(9);
1982 this.add(cos, sin, -sin, cos, x, y);
1983 this.add(1, 0, 0, 1, -x, -y);
1989 * Return x coordinate for given point after transformation described by the matrix. See also @Matrix.y
1995 matrixproto.x = function (x, y) {
1996 return x * this.a + y * this.c + this.e;
2002 * Return y coordinate for given point after transformation described by the matrix. See also @Matrix.x
2008 matrixproto.y = function (x, y) {
2009 return x * this.b + y * this.d + this.f;
2011 matrixproto.get = function (i) {
2012 return +this[Str.fromCharCode(97 + i)].toFixed(4);
2014 matrixproto.toString = function () {
2016 "matrix(" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)].join() + ")" :
2017 [this.get(0), this.get(2), this.get(1), this.get(3), 0, 0].join();
2019 matrixproto.toFilter = function () {
2020 return "progid:DXImageTransform.Microsoft.Matrix(M11=" + this.get(0) +
2021 ", M12=" + this.get(2) + ", M21=" + this.get(1) + ", M22=" + this.get(3) +
2022 ", Dx=" + this.get(4) + ", Dy=" + this.get(5) + ", sizingmethod='auto expand')";
2024 matrixproto.offset = function () {
2025 return [this.e.toFixed(4), this.f.toFixed(4)];
2028 return a[0] * a[0] + a[1] * a[1];
2030 function normalize(a) {
2031 var mag = math.sqrt(norm(a));
2032 a[0] && (a[0] /= mag);
2033 a[1] && (a[1] /= mag);
2039 * Splits matrix into primitive transformations
2040 = (object) in format:
2041 o dx (number) translation by x
2042 o dy (number) translation by y
2043 o scalex (number) scale by x
2044 o scaley (number) scale by y
2045 o shear (number) shear
2046 o rotate (number) rotation in deg
2047 o isSimple (boolean) could it be represented via simple transformations
2049 matrixproto.split = function () {
2056 var row = [[this.a, this.c], [this.b, this.d]];
2057 out.scalex = math.sqrt(norm(row[0]));
2060 out.shear = row[0][0] * row[1][0] + row[0][1] * row[1][1];
2061 row[1] = [row[1][0] - row[0][0] * out.shear, row[1][1] - row[0][1] * out.shear];
2063 out.scaley = math.sqrt(norm(row[1]));
2065 out.shear /= out.scaley;
2068 var sin = -row[0][1],
2071 out.rotate = R.deg(math.acos(cos));
2073 out.rotate = 360 - out.rotate;
2076 out.rotate = R.deg(math.asin(sin));
2079 out.isSimple = !+out.shear.toFixed(9) && (out.scalex.toFixed(9) == out.scaley.toFixed(9) || !out.rotate);
2080 out.isSuperSimple = !+out.shear.toFixed(9) && out.scalex.toFixed(9) == out.scaley.toFixed(9) && !out.rotate;
2081 out.noRotation = !+out.shear.toFixed(9) && !out.rotate;
2085 * Matrix.toTransformString
2088 * Return transform string that represents given matrix
2089 = (string) transform string
2091 matrixproto.toTransformString = function () {
2092 var s = this.split();
2094 return "t" + [s.dx, s.dy] + "s" + [s.scalex, s.scaley, 0, 0] + "r" + [s.rotate, 0, 0];
2096 return "m" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)];
2099 })(Matrix.prototype);
2101 // WebKit rendering bug workaround method
2102 var version = navigator.userAgent.match(/Version\/(.*?)\s/) || navigator.userAgent.match(/Chrome\/(\d+)/);
2103 if ((navigator.vendor == "Apple Computer, Inc.") && (version && version[1] < 4 || navigator.platform.slice(0, 2) == "iP") ||
2104 (navigator.vendor == "Google Inc." && version && version[1] < 8)) {
2109 * There is an inconvenient rendering bug in Safari (WebKit):
2110 * sometimes the rendering should be forced.
2111 * This method should help with dealing with this bug.
2113 paperproto.safari = function () {
2114 var rect = this.rect(-99, -99, this.width + 99, this.height + 99).attr({stroke: "none"});
2115 setTimeout(function () {rect.remove();});
2118 paperproto.safari = fun;
2122 var preventDefault = function () {
2123 this.returnValue = false;
2125 preventTouch = function () {
2126 return this.originalEvent.preventDefault();
2128 stopPropagation = function () {
2129 this.cancelBubble = true;
2131 stopTouch = function () {
2132 return this.originalEvent.stopPropagation();
2134 addEvent = (function () {
2135 if (g.doc.addEventListener) {
2136 return function (obj, type, fn, element) {
2137 var realName = supportsTouch && touchMap[type] ? touchMap[type] : type,
2139 var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
2140 scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft,
2141 x = e.clientX + scrollX,
2142 y = e.clientY + scrollY;
2143 if (supportsTouch && touchMap[has](type)) {
2144 for (var i = 0, ii = e.targetTouches && e.targetTouches.length; i < ii; i++) {
2145 if (e.targetTouches[i].target == obj) {
2147 e = e.targetTouches[i];
2148 e.originalEvent = olde;
2149 e.preventDefault = preventTouch;
2150 e.stopPropagation = stopTouch;
2155 return fn.call(element, e, x, y);
2157 obj.addEventListener(realName, f, false);
2158 return function () {
2159 obj.removeEventListener(realName, f, false);
2163 } else if (g.doc.attachEvent) {
2164 return function (obj, type, fn, element) {
2165 var f = function (e) {
2166 e = e || g.win.event;
2167 var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
2168 scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft,
2169 x = e.clientX + scrollX,
2170 y = e.clientY + scrollY;
2171 e.preventDefault = e.preventDefault || preventDefault;
2172 e.stopPropagation = e.stopPropagation || stopPropagation;
2173 return fn.call(element, e, x, y);
2175 obj.attachEvent("on" + type, f);
2176 var detacher = function () {
2177 obj.detachEvent("on" + type, f);
2185 dragMove = function (e) {
2188 scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
2189 scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft,
2194 if (supportsTouch) {
2195 var i = e.touches.length,
2198 touch = e.touches[i];
2199 if (touch.identifier == dragi.el._drag.id) {
2202 (e.originalEvent ? e.originalEvent : e).preventDefault();
2209 var node = dragi.el.node,
2211 next = node.nextSibling,
2212 parent = node.parentNode,
2213 display = node.style.display;
2214 g.win.opera && parent.removeChild(node);
2215 node.style.display = "none";
2216 o = dragi.el.paper.getElementByPoint(x, y);
2217 node.style.display = display;
2218 g.win.opera && (next ? parent.insertBefore(node, next) : parent.appendChild(node));
2219 o && eve("drag.over." + dragi.el.id, dragi.el, o);
2222 eve("drag.move." + dragi.el.id, dragi.move_scope || dragi.el, x - dragi.el._drag.x, y - dragi.el._drag.y, x, y, e);
2225 dragUp = function (e) {
2226 R.unmousemove(dragMove).unmouseup(dragUp);
2227 var i = drag.length,
2231 dragi.el._drag = {};
2232 eve("drag.end." + dragi.el.id, dragi.end_scope || dragi.start_scope || dragi.move_scope || dragi.el, e);
2238 [ property (object) ]
2240 * You can add your own method to elements. This is usefull when you want to hack default functionality or
2241 * want to wrap some common transformation or attributes in one method. In difference to canvas methods,
2242 * you can redefine element method at any time. Expending element methods wouldn’t affect set.
2244 | Raphael.el.red = function () {
2245 | this.attr({fill: "#f00"});
2248 | paper.circle(100, 100, 20).red();
2250 elproto = R.el = {};
2251 for (var i = events.length; i--;) {
2252 (function (eventName) {
2253 R[eventName] = elproto[eventName] = function (fn, scope) {
2254 if (R.is(fn, "function")) {
2255 this.events = this.events || [];
2256 this.events.push({name: eventName, f: fn, unbind: addEvent(this.shape || this.node || g.doc, eventName, fn, scope || this)});
2260 R["un" + eventName] = elproto["un" + eventName] = function (fn) {
2261 var events = this.events,
2263 while (l--) if (events[l].name == eventName && events[l].f == fn) {
2265 events.splice(l, 1);
2266 !events.length && delete this.events;
2278 * Adds or retrieves given value asociated with given key.
2280 * See also @Element.removeData
2282 - key (string) key to store data
2283 - value (any) #optional value to store
2285 * or, if value is not specified:
2288 | for (var i = 0, i < 5, i++) {
2289 | paper.circle(10 + 15 * i, 10, 10)
2290 | .attr({fill: "#000"})
2292 | .click(function () {
2293 | alert(this.data("i"));
2297 elproto.data = function (key, value) {
2298 var data = eldata[this.id] = eldata[this.id] || {};
2299 if (arguments.length == 1) {
2300 if (R.is(key, "object")) {
2301 for (var i in key) if (key[has](i)) {
2302 this.data(i, key[i]);
2306 eve("data.get." + this.id, this, data[key], key);
2310 eve("data.set." + this.id, this, value, key);
2314 * Element.removeData
2317 * Removes value associated with an element by given key.
2318 * If key is not provided, removes all the data of the element.
2320 - key (string) #optional key
2323 elproto.removeData = function (key) {
2325 eldata[this.id] = {};
2327 eldata[this.id] && delete eldata[this.id][key];
2335 * Adds event handlers for hover for the element.
2337 - f_in (function) handler for hover in
2338 - f_out (function) handler for hover out
2339 - icontext (object) #optional context for hover in handler
2340 - ocontext (object) #optional context for hover out handler
2343 elproto.hover = function (f_in, f_out, scope_in, scope_out) {
2344 return this.mouseover(f_in, scope_in).mouseout(f_out, scope_out || scope_in);
2350 * Removes event handlers for hover for the element.
2352 - f_in (function) handler for hover in
2353 - f_out (function) handler for hover out
2356 elproto.unhover = function (f_in, f_out) {
2357 return this.unmouseover(f_in).unmouseout(f_out);
2363 * Adds event handlers for drag of the element.
2365 - onmove (function) handler for moving
2366 - onstart (function) handler for drag start
2367 - onend (function) handler for drag end
2368 - mcontext (object) #optional context for moving handler
2369 - scontext (object) #optional context for drag start handler
2370 - econtext (object) #optional context for drag end handler
2371 * Additionaly following `drag` events will be triggered: `drag.start.<id>` on start,
2372 * `drag.end.<id>` on end and `drag.move.<id>` on every move. When element will be dragged over another element
2373 * `drag.over.<id>` will be fired as well.
2375 * Start event and start handler will be called in specified context or in context of the element with following parameters:
2376 o x (number) x position of the mouse
2377 o y (number) y position of the mouse
2378 o event (object) DOM event object
2379 * Move event and move handler will be called in specified context or in context of the element with following parameters:
2380 o dx (number) shift by x from the start point
2381 o dy (number) shift by y from the start point
2382 o x (number) x position of the mouse
2383 o y (number) y position of the mouse
2384 o event (object) DOM event object
2385 * End event and end handler will be called in specified context or in context of the element with following parameters:
2386 o event (object) DOM event object
2389 elproto.drag = function (onmove, onstart, onend, move_scope, start_scope, end_scope) {
2391 (e.originalEvent || e).preventDefault();
2392 var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
2393 scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft;
2394 this._drag.x = e.clientX + scrollX;
2395 this._drag.y = e.clientY + scrollY;
2396 this._drag.id = e.identifier;
2397 !drag.length && R.mousemove(dragMove).mouseup(dragUp);
2398 drag.push({el: this, move_scope: move_scope, start_scope: start_scope, end_scope: end_scope});
2399 onstart && eve.on("drag.start." + this.id, onstart);
2400 onmove && eve.on("drag.move." + this.id, onmove);
2401 onend && eve.on("drag.end." + this.id, onend);
2402 eve("drag.start." + this.id, start_scope || move_scope || this, e.clientX + scrollX, e.clientY + scrollY, e);
2405 this.mousedown(start);
2409 * Element.onDragOver
2412 * Shortcut for assigning event handler for `drag.over.<id>` event, where id is id of the element (see @Element.id).
2414 - f (function) handler for event
2416 elproto.onDragOver = function (f) {
2417 f ? eve.on("drag.over." + this.id, f) : eve.unbind("drag.over." + this.id);
2423 * Removes all drag event handlers from given element.
2425 elproto.undrag = function () {
2426 var i = drag.length;
2427 while (i--) if (drag[i].el == this) {
2428 R.unmousedown(drag[i].start);
2429 drag.splice(i++, 1);
2430 eve.unbind("drag.*." + this.id);
2432 !drag.length && R.unmousemove(dragMove).unmouseup(dragUp);
2442 - x (number) x coordinate of the centre
2443 - y (number) y coordinate of the centre
2445 = (object) Raphaël element object with type “circle”
2448 | var c = paper.circle(50, 50, 40);
2450 paperproto.circle = function (x, y, r) {
2451 var out = R._engine.circle(this, x || 0, y || 0, r || 0);
2452 this.__set__ && this.__set__.push(out);
2459 * Draws a rectangle.
2463 - x (number) x coordinate of the top left corner
2464 - y (number) y coordinate of the top left corner
2465 - width (number) width
2466 - height (number) height
2467 - r (number) #optional radius for rounded corners, default is 0
2468 = (object) Raphaël element object with type “rect”
2471 | // regular rectangle
2472 | var c = paper.rect(10, 10, 50, 50);
2473 | // rectangle with rounded corners
2474 | var c = paper.rect(40, 40, 50, 50, 10);
2476 paperproto.rect = function (x, y, w, h, r) {
2477 var out = R._engine.rect(this, x || 0, y || 0, w || 0, h || 0, r || 0);
2478 this.__set__ && this.__set__.push(out);
2489 - x (number) x coordinate of the centre
2490 - y (number) y coordinate of the centre
2491 - rx (number) horizontal radius
2492 - ry (number) vertical radius
2493 = (object) Raphaël element object with type “ellipse”
2496 | var c = paper.ellipse(50, 50, 40, 20);
2498 paperproto.ellipse = function (x, y, rx, ry) {
2499 var out = R._engine.ellipse(this, x || 0, y || 0, rx || 0, ry || 0);
2500 this.__set__ && this.__set__.push(out);
2507 * Creates a path element by given path data string.
2511 - pathString (string) path data in SVG path string format.
2512 = (object) Raphaël element object with type “path”
2513 # Details of a path's data attribute's format are described in the <a href="http://www.w3.org/TR/SVG/paths.html#PathData">SVG specification</a>.
2516 | var c = paper.path("M10 10L90 90");
2517 | // draw a diagonal line:
2518 | // move to 10,10, line to 90,90
2520 paperproto.path = function (pathString) {
2521 pathString && !R.is(pathString, string) && !R.is(pathString[0], array) && (pathString += E);
2522 var out = R._engine.path(R.format[apply](R, arguments), this);
2523 this.__set__ && this.__set__.push(out);
2530 * Embeds an image into the surface.
2534 - src (string) URI of the source image
2535 - x (number) x coordinate position
2536 - y (number) y coordinate position
2537 - width (number) width of the image
2538 - height (number) height of the image
2539 = (object) Raphaël element object with type “image”
2542 | var c = paper.image("apple.png", 10, 10, 80, 80);
2544 paperproto.image = function (src, x, y, w, h) {
2545 var out = R._engine.image(this, src || "about:blank", x || 0, y || 0, w || 0, h || 0);
2546 this.__set__ && this.__set__.push(out);
2553 * Draws a text string. If you need line breaks, put “\n” in the string.
2557 - x (number) x coordinate position
2558 - y (number) y coordinate position
2559 - text (string) The text string to draw
2560 = (object) Raphaël element object with type “text”
2563 | var t = paper.text(50, 50, "Raphaël\nkicks\nbutt!");
2565 paperproto.text = function (x, y, text) {
2566 var out = R._engine.text(this, x || 0, y || 0, Str(text));
2567 this.__set__ && this.__set__.push(out);
2574 * Creates array-like object to keep and operate several elements at once.
2575 * Warning: it doesn’t create any elements for itself in the page, it just groups existing elements.
2576 * Sets act as pseudo elements — all methods available to an element can be used on a set.
2577 = (object) array-like object that represents set of elements
2580 | var st = paper.set();
2582 | paper.circle(10, 10, 5),
2583 | paper.circle(30, 10, 5)
2585 | st.attr({fill: "red"}); // changes the fill of both circles
2587 paperproto.set = function (itemsArray) {
2588 !R.is(itemsArray, "array") && (itemsArray = Array.prototype.splice.call(arguments, 0, arguments.length));
2589 var out = new Set(itemsArray);
2590 this.__set__ && this.__set__.push(out);
2597 * Creates @Paper.set. All elements that will be created after calling this method and before calling
2598 * @Paper.setFinish will be added to the set.
2602 | paper.circle(10, 10, 5),
2603 | paper.circle(30, 10, 5)
2604 | var st = paper.setFinish();
2605 | st.attr({fill: "red"}); // changes the fill of both circles
2607 paperproto.setStart = function (set) {
2608 this.__set__ = set || this.set();
2614 * See @Paper.setStart. This method finishes catching and returns resulting set.
2618 paperproto.setFinish = function (set) {
2619 var out = this.__set__;
2620 delete this.__set__;
2627 * If you need to change dimensions of the canvas call this method
2631 - width (number) new width of the canvas
2632 - height (number) new height of the canvas
2634 | var st = paper.set();
2636 | paper.circle(10, 10, 5),
2637 | paper.circle(30, 10, 5)
2639 | st.attr({fill: "red"});
2641 paperproto.setSize = R._engine.setSize;
2646 * Sets the view box of the paper. Practically it gives you ability to zoom and pan whole paper surface by
2647 * specifying new boundaries.
2652 - x (number) new x position, default is `0`
2653 - y (number) new y position, default is `0`
2654 - w (number) new width of the canvas
2655 - h (number) new height of the canvas
2656 - fit (boolean) `true` if you want graphics to fit into new boundary box
2658 paperproto.setViewBox = R._engine.setViewBox;
2663 * Points to the topmost element on the paper
2669 * Points to the bottom element on the paper
2671 paperproto.top = paperproto.bottom = null;
2676 * Points to the @Raphael object/function
2678 paperproto.raphael = R;
2679 var getOffset = function (elem) {
2680 var box = elem.getBoundingClientRect(),
2681 doc = elem.ownerDocument,
2683 docElem = doc.documentElement,
2684 clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0,
2685 top = box.top + (g.win.pageYOffset || docElem.scrollTop || body.scrollTop ) - clientTop,
2686 left = box.left + (g.win.pageXOffset || docElem.scrollLeft || body.scrollLeft) - clientLeft;
2693 * Paper.getElementByPoint
2696 * Returns you topmost element under given point.
2698 = (object) Raphaël element object
2701 - x (number) x coordinate from the top left corner of the window
2702 - y (number) y coordinate from the top left corner of the window
2704 | paper.getElementByPoint(mouseX, mouseY).attr({stroke: "#f00"});
2706 paperproto.getElementByPoint = function (x, y) {
2709 target = g.doc.elementFromPoint(x, y);
2710 if (g.win.opera && target.tagName == "svg") {
2711 var so = getOffset(svg),
2712 sr = svg.createSVGRect();
2715 sr.width = sr.height = 1;
2716 var hits = svg.getIntersectionList(sr, null);
2718 target = hits[hits.length - 1];
2724 while (target.parentNode && target != svg.parentNode && !target.raphael) {
2725 target = target.parentNode;
2727 target == paper.canvas.parentNode && (target = svg);
2728 target = target && target.raphael ? paper.getById(target.raphaelid) : null;
2735 * Returns you element by its internal ID.
2740 = (object) Raphaël element object
2742 paperproto.getById = function (id) {
2743 var bot = this.bottom;
2756 * Executes given function for each element on the paper
2758 * If callback function returns `false` it will stop loop running.
2762 - callback (function) function to run
2763 - thisArg (object) context object for the callback
2764 = (object) Paper object
2766 paperproto.forEach = function (callback, thisArg) {
2767 var bot = this.bottom;
2769 if (callback.call(thisArg, bot) === false) {
2777 return this.x + S + this.y;
2779 function x_y_w_h() {
2780 return this.x + S + this.y + S + this.width + " \xd7 " + this.height;
2786 * Return bounding box for a given element
2790 - isWithoutTransform (boolean) flag, `true` if you want to have bounding box before transformations. Default is `false`.
2791 = (object) Bounding box object:
2793 o x: (number) top left corner x
2794 o y: (number) top left corner y
2795 o width: (number) width
2796 o height: (number) height
2799 elproto.getBBox = function (isWithoutTransform) {
2804 if (isWithoutTransform) {
2805 if (_.dirty || !_.bboxwt) {
2806 this.realPath = getPath[this.type](this);
2807 _.bboxwt = pathDimensions(this.realPath);
2808 _.bboxwt.toString = x_y_w_h;
2813 if (_.dirty || _.dirtyT || !_.bbox) {
2814 if (_.dirty || !this.realPath) {
2816 this.realPath = getPath[this.type](this);
2818 _.bbox = pathDimensions(mapPath(this.realPath, this.matrix));
2819 _.bbox.toString = x_y_w_h;
2820 _.dirty = _.dirtyT = 0;
2828 = (object) clone of a given element
2831 elproto.clone = function () {
2835 return this.paper[this.type]().attr(this.attr());
2841 * Return set of elements that create glow-like effect around given element. See @Paper.set.
2843 * Note: Glow is not connected to the element. If you change element attributes it won’t adjust itself.
2847 - glow (object) #optional parameters object with all properties optional:
2849 o width (number) size of the glow, default is `10`
2850 o fill (boolean) will it be filled, default is `false`
2851 o opacity (number) opacity, default is `0.5`
2852 o offsetx (number) horizontal offset, default is `0`
2853 o offsety (number) vertical offset, default is `0`
2854 o color (string) glow colour, default is `black`
2856 = (object) @Paper.set of elements that represents glow
2858 elproto.glow = function (glow) {
2859 if (this.type == "text") {
2864 width: (glow.width || 10) + (+this.attr("stroke-width") || 1),
2865 fill: glow.fill || false,
2866 opacity: glow.opacity || .5,
2867 offsetx: glow.offsetx || 0,
2868 offsety: glow.offsety || 0,
2869 color: glow.color || "#000"
2874 path = this.realPath || getPath[this.type](this);
2875 path = this.matrix ? mapPath(path, this.matrix) : path;
2876 for (var i = 1; i < c + 1; i++) {
2877 out.push(r.path(path).attr({
2879 fill: s.fill ? s.color : "none",
2880 "stroke-linejoin": "round",
2881 "stroke-linecap": "round",
2882 "stroke-width": +(s.width / c * i).toFixed(3),
2883 opacity: +(s.opacity / c).toFixed(3)
2886 return out.insertBefore(this).translate(s.offsetx, s.offsety);
2888 var curveslengths = {},
2889 getPointAtSegmentLength = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length) {
2892 name = [p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y].join(),
2893 cache = curveslengths[name],
2895 !cache && (curveslengths[name] = cache = {data: []});
2896 cache.timer && clearTimeout(cache.timer);
2897 cache.timer = setTimeout(function () {delete curveslengths[name];}, 2e3);
2898 if (length != null && !cache.precision) {
2899 var total = getPointAtSegmentLength(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y);
2900 cache.precision = ~~total * 10;
2903 precision = cache.precision || precision;
2904 for (var i = 0; i < precision + 1; i++) {
2905 if (cache.data[i * precision]) {
2906 dot = cache.data[i * precision];
2908 dot = R.findDotsAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, i / precision);
2909 cache.data[i * precision] = dot;
2911 i && (len += pow(pow(old.x - dot.x, 2) + pow(old.y - dot.y, 2), .5));
2912 if (length != null && len >= length) {
2917 if (length == null) {
2921 getLengthFactory = function (istotal, subpath) {
2922 return function (path, length, onlystart) {
2923 path = path2curve(path);
2924 var x, y, p, l, sp = "", subpaths = {}, point,
2926 for (var i = 0, ii = path.length; i < ii; i++) {
2932 l = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6]);
2933 if (len + l > length) {
2934 if (subpath && !subpaths.start) {
2935 point = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6], length - len);
2936 sp += ["C" + point.start.x, point.start.y, point.m.x, point.m.y, point.x, point.y];
2937 if (onlystart) {return sp;}
2938 subpaths.start = sp;
2939 sp = ["M" + point.x, point.y + "C" + point.n.x, point.n.y, point.end.x, point.end.y, p[5], p[6]].join();
2945 if (!istotal && !subpath) {
2946 point = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6], length - len);
2947 return {x: point.x, y: point.y, alpha: point.alpha};
2954 sp += p.shift() + p;
2957 point = istotal ? len : subpath ? subpaths : R.findDotsAtSegment(x, y, p[1], p[2], p[3], p[4], p[5], p[6], 1);
2958 point.alpha && (point = {x: point.x, y: point.y, alpha: point.alpha});
2962 var getTotalLength = getLengthFactory(1),
2963 getPointAtLength = getLengthFactory(),
2964 getSubpathsAtLength = getLengthFactory(0, 1);
2966 * Raphael.getTotalLength
2969 * Returns length of the given path in pixels.
2973 - path (string) SVG path string.
2977 R.getTotalLength = getTotalLength;
2979 * Raphael.getPointAtLength
2982 * Return coordinates of the point located at the given length on the given path.
2986 - path (string) SVG path string
2989 = (object) representation of the point:
2991 o x: (number) x coordinate
2992 o y: (number) y coordinate
2993 o alpha: (number) angle of derivative
2996 R.getPointAtLength = getPointAtLength;
2998 * Raphael.getSubpath
3001 * Return subpath of a given path from given length to given length.
3005 - path (string) SVG path string
3006 - from (number) position of the start of the segment
3007 - to (number) position of the end of the segment
3009 = (string) pathstring for the segment
3011 R.getSubpath = function (path, from, to) {
3012 if (abs(this.getTotalLength(path) - to) < 1e-6) {
3013 return getSubpathsAtLength(path, from).end;
3015 var a = getSubpathsAtLength(path, to, 1);
3016 return from ? getSubpathsAtLength(a, from).end : a;
3019 * Element.getTotalLength
3022 * Returns length of the path in pixels. Only works for element of “path” type.
3025 elproto.getTotalLength = function () {
3026 if (this.type != "path") {return;}
3027 if (this.node.getTotalLength) {
3028 return this.node.getTotalLength();
3030 return getTotalLength(this.attrs.path);
3033 * Element.getPointAtLength
3036 * Return coordinates of the point located at the given length on the given path. Only works for element of “path” type.
3042 = (object) representation of the point:
3044 o x: (number) x coordinate
3045 o y: (number) y coordinate
3046 o alpha: (number) angle of derivative
3049 elproto.getPointAtLength = function (length) {
3050 if (this.type != "path") {return;}
3051 return getPointAtLength(this.attrs.path, length);
3054 * Element.getSubpath
3057 * Return subpath of a given element from given length to given length. Only works for element of “path” type.
3061 - from (number) position of the start of the segment
3062 - to (number) position of the end of the segment
3064 = (string) pathstring for the segment
3066 elproto.getSubpath = function (from, to) {
3067 if (this.type != "path") {return;}
3068 return R.getSubpath(this.attrs.path, from, to);
3071 * Raphael.easing_formulas
3074 * Object that contains easing formulas for animation. You could extend it with your own. By default it has following list of easing:
3077 # <li>“<” or “easeIn” or “ease-in”</li>
3078 # <li>“>” or “easeOut” or “ease-out”</li>
3079 # <li>“<>” or “easeInOut” or “ease-in-out”</li>
3080 # <li>“backIn” or “back-in”</li>
3081 # <li>“backOut” or “back-out”</li>
3082 # <li>“elastic”</li>
3085 # <p>See also <a href="http://raphaeljs.com/easing.html">Easing demo</a>.</p>
3087 var ef = R.easing_formulas = {
3088 linear: function (n) {
3097 "<>": function (n) {
3098 var q = .48 - n / 1.04,
3099 Q = math.sqrt(.1734 + q * q),
3101 X = pow(abs(x), 1 / 3) * (x < 0 ? -1 : 1),
3103 Y = pow(abs(y), 1 / 3) * (y < 0 ? -1 : 1),
3105 return (1 - t) * 3 * t * t + t * t * t;
3107 backIn: function (n) {
3109 return n * n * ((s + 1) * n - s);
3111 backOut: function (n) {
3114 return n * n * ((s + 1) * n + s) + 1;
3116 elastic: function (n) {
3120 return pow(2, -10 * n) * math.sin((n - .075) * (2 * PI) / .3) + 1;
3122 bounce: function (n) {
3131 l = s * n * n + .75;
3133 if (n < (2.5 / p)) {
3135 l = s * n * n + .9375;
3138 l = s * n * n + .984375;
3145 ef.easeIn = ef["ease-in"] = ef["<"];
3146 ef.easeOut = ef["ease-out"] = ef[">"];
3147 ef.easeInOut = ef["ease-in-out"] = ef["<>"];
3148 ef["back-in"] = ef.backIn;
3149 ef["back-out"] = ef.backOut;
3151 var animationElements = [],
3152 requestAnimFrame = window.requestAnimationFrame ||
3153 window.webkitRequestAnimationFrame ||
3154 window.mozRequestAnimationFrame ||
3155 window.oRequestAnimationFrame ||
3156 window.msRequestAnimationFrame ||
3157 function (callback) {
3158 setTimeout(callback, 16);
3160 animation = function () {
3161 var Now = +new Date,
3163 for (; l < animationElements.length; l++) {
3164 var e = animationElements[l];
3165 if (e.el.removed || e.paused) {
3168 var time = Now - e.start,
3179 time = (e.initstatus * e.anim.top - e.prev) / (e.percent - e.prev) * ms;
3180 e.status = e.initstatus;
3181 delete e.initstatus;
3182 e.stop && animationElements.splice(l--, 1);
3184 e.status = (e.prev + (e.percent - e.prev) * (time / ms)) / e.anim.top;
3190 var pos = easing(time / ms);
3191 for (var attr in from) if (from[has](attr)) {
3192 switch (availableAnimAttrs[attr]) {
3194 now = +from[attr] + pos * ms * diff[attr];
3198 upto255(round(from[attr].r + pos * ms * diff[attr].r)),
3199 upto255(round(from[attr].g + pos * ms * diff[attr].g)),
3200 upto255(round(from[attr].b + pos * ms * diff[attr].b))
3205 for (var i = 0, ii = from[attr].length; i < ii; i++) {
3206 now[i] = [from[attr][i][0]];
3207 for (var j = 1, jj = from[attr][i].length; j < jj; j++) {
3208 now[i][j] = +from[attr][i][j] + pos * ms * diff[attr][i][j];
3210 now[i] = now[i].join(S);
3215 if (diff[attr].real) {
3217 for (i = 0, ii = from[attr].length; i < ii; i++) {
3218 now[i] = [from[attr][i][0]];
3219 for (j = 1, jj = from[attr][i].length; j < jj; j++) {
3220 now[i][j] = from[attr][i][j] + pos * ms * diff[attr][i][j];
3224 var get = function (i) {
3225 return +from[attr][i] + pos * ms * diff[attr][i];
3227 // now = [["r", get(2), 0, 0], ["t", get(3), get(4)], ["s", get(0), get(1), 0, 0]];
3228 now = [["m", get(0), get(1), get(2), get(3), get(4), get(5)]];
3232 if (attr == "clip-rect") {
3236 now[i] = +from[attr][i] + pos * ms * diff[attr][i];
3241 var from2 = [].concat(from[attr]);
3243 i = that.paper.customAttributes[attr].length;
3245 now[i] = +from2[i] + pos * ms * diff[attr][i];
3252 (function (id, that, anim) {
3253 setTimeout(function () {
3254 eve("anim.frame." + id, that, anim);
3256 })(that.id, that, e.anim);
3258 (function(f, el, a) {
3259 setTimeout(function() {
3260 eve("anim.frame." + el.id, el, a);
3261 eve("anim.finish." + el.id, el, a);
3262 R.is(f, "function") && f.call(el);
3264 })(e.callback, that, e.anim);
3266 animationElements.splice(l--, 1);
3267 if (e.repeat > 1 && !e.next) {
3268 runAnimation(e.anim, e.el, e.anim.percents[0], null, e.totalOrigin, e.repeat - 1);
3270 if (e.next && !e.stop) {
3271 runAnimation(e.anim, e.el, e.next, null, e.totalOrigin, e.repeat);
3275 R.svg && that && that.paper && that.paper.safari();
3276 animationElements.length && requestAnimFrame(animation);
3278 upto255 = function (color) {
3279 return color > 255 ? 255 : color < 0 ? 0 : color;
3282 * Element.animateWith
3285 * Acts similar to @Element.animate, but ensure that given animation runs in sync with another given element.
3289 - params (object) final attributes for the element, see also @Element.attr
3290 - ms (number) number of milliseconds for animation to run
3291 - easing (string) #optional easing type. Accept on of @Raphael.easing_formulas or CSS format: `cubic‐bezier(XX, XX, XX, XX)`
3292 - callback (function) #optional callback function. Will be called at the end of animation.
3294 - animation (object) animation object, see @Raphael.animation
3296 = (object) original element
3298 elproto.animateWith = function (element, params, ms, easing, callback) {
3299 this.animate(params, ms, easing, callback);
3301 for (var i = 0, ii = animationElements.length; i < ii; i++) {
3302 el = animationElements[i];
3303 if (el.el.id == element.id) {
3304 start = el.timestamp;
3305 } else if (el.el.id == this.id) {
3309 return this.animate(params, ms, easing, callback);
3311 function CubicBezierAtTime(t, p1x, p1y, p2x, p2y, duration) {
3313 bx = 3 * (p2x - p1x) - cx,
3316 by = 3 * (p2y - p1y) - cy,
3318 function sampleCurveX(t) {
3319 return ((ax * t + bx) * t + cx) * t;
3321 function solve(x, epsilon) {
3322 var t = solveCurveX(x, epsilon);
3323 return ((ay * t + by) * t + cy) * t;
3325 function solveCurveX(x, epsilon) {
3326 var t0, t1, t2, x2, d2, i;
3327 for(t2 = x, i = 0; i < 8; i++) {
3328 x2 = sampleCurveX(t2) - x;
3329 if (abs(x2) < epsilon) {
3332 d2 = (3 * ax * t2 + 2 * bx) * t2 + cx;
3333 if (abs(d2) < 1e-6) {
3348 x2 = sampleCurveX(t2);
3349 if (abs(x2 - x) < epsilon) {
3357 t2 = (t1 - t0) / 2 + t0;
3361 return solve(t, 1 / (200 * duration));
3363 elproto.onAnimation = function (f) {
3364 f ? eve.on("anim.frame." + this.id, f) : eve.unbind("anim.frame." + this.id);
3367 function Animation(anim, ms) {
3373 for (var attr in this.anim) if (this.anim[has](attr)) {
3374 percents.push(+attr);
3376 percents.sort(sortByNumber);
3378 this.top = percents[percents.length - 1];
3379 this.percents = percents;
3385 * Creates a copy of existing animation object with given delay.
3389 - delay (number) number of ms to pass between animation start and actual animation
3391 = (object) new altered Animation object
3393 Animation.prototype.delay = function (delay) {
3394 var a = new Animation(this.anim, this.ms);
3395 a.times = this.times;
3396 a.del = +delay || 0;
3403 * Creates a copy of existing animation object with given repetition.
3407 - repeat (number) number iterations of animation. For infinite animation pass `Infinity`
3409 = (object) new altered Animation object
3411 Animation.prototype.repeat = function (times) {
3412 var a = new Animation(this.anim, this.ms);
3414 a.times = math.floor(mmax(times, 0)) || 1;
3417 function runAnimation(anim, element, percent, status, totalOrigin, times) {
3418 percent = toFloat(percent);
3431 for (i = 0, ii = animationElements.length; i < ii; i++) {
3432 var e = animationElements[i];
3433 if (e.el.id == element.id && e.anim == anim) {
3434 if (e.percent != percent) {
3435 animationElements.splice(i, 1);
3440 element.attr(e.totalOrigin);
3445 status = +to; // NaN
3447 for (var i = 0, ii = anim.percents.length; i < ii; i++) {
3448 if (anim.percents[i] == percent || anim.percents[i] > status * anim.top) {
3449 percent = anim.percents[i];
3450 prev = anim.percents[i - 1] || 0;
3451 ms = ms / anim.top * (percent - prev);
3452 next = anim.percents[i + 1];
3453 params = anim.anim[percent];
3455 } else if (status) {
3456 element.attr(anim.anim[anim.percents[i]]);
3463 for (attr in params) if (params[has](attr)) {
3464 if (availableAnimAttrs[has](attr) || element.paper.customAttributes[has](attr)) {
3465 from[attr] = element.attr(attr);
3466 (from[attr] == null) && (from[attr] = availableAttrs[attr]);
3467 to[attr] = params[attr];
3468 switch (availableAnimAttrs[attr]) {
3470 diff[attr] = (to[attr] - from[attr]) / ms;
3473 from[attr] = R.getRGB(from[attr]);
3474 var toColour = R.getRGB(to[attr]);
3476 r: (toColour.r - from[attr].r) / ms,
3477 g: (toColour.g - from[attr].g) / ms,
3478 b: (toColour.b - from[attr].b) / ms
3482 var pathes = path2curve(from[attr], to[attr]),
3484 from[attr] = pathes[0];
3486 for (i = 0, ii = from[attr].length; i < ii; i++) {
3487 diff[attr][i] = [0];
3488 for (var j = 1, jj = from[attr][i].length; j < jj; j++) {
3489 diff[attr][i][j] = (toPath[i][j] - from[attr][i][j]) / ms;
3495 eq = equaliseTransform(_[attr], to[attr]);
3497 from[attr] = eq.from;
3500 diff[attr].real = true;
3501 for (i = 0, ii = from[attr].length; i < ii; i++) {
3502 diff[attr][i] = [from[attr][i][0]];
3503 for (j = 1, jj = from[attr][i].length; j < jj; j++) {
3504 diff[attr][i][j] = (to[attr][i][j] - from[attr][i][j]) / ms;
3508 var m = (element.matrix || new Matrix),
3510 _: {transform: _.transform},
3511 getBBox: function () {
3512 return element.getBBox(1);
3523 extractTransform(to2, to[attr]);
3524 to[attr] = to2._.transform;
3526 (to2.matrix.a - m.a) / ms,
3527 (to2.matrix.b - m.b) / ms,
3528 (to2.matrix.c - m.c) / ms,
3529 (to2.matrix.d - m.d) / ms,
3530 (to2.matrix.e - m.e) / ms,
3531 (to2.matrix.e - m.f) / ms
3533 // from[attr] = [_.sx, _.sy, _.deg, _.dx, _.dy];
3534 // var to2 = {_:{}, getBBox: function () { return element.getBBox(); }};
3535 // extractTransform(to2, to[attr]);
3537 // (to2._.sx - _.sx) / ms,
3538 // (to2._.sy - _.sy) / ms,
3539 // (to2._.deg - _.deg) / ms,
3540 // (to2._.dx - _.dx) / ms,
3541 // (to2._.dy - _.dy) / ms
3546 var values = Str(params[attr]).split(separator),
3547 from2 = Str(from[attr]).split(separator);
3548 if (attr == "clip-rect") {
3553 diff[attr][i] = (values[i] - from[attr][i]) / ms;
3559 values = [].concat(params[attr]);
3560 from2 = [].concat(from[attr]);
3562 i = element.paper.customAttributes[attr].length;
3564 diff[attr][i] = ((values[i] || 0) - (from2[i] || 0)) / ms;
3570 var easing = params.easing,
3571 easyeasy = R.easing_formulas[easing];
3573 easyeasy = Str(easing).match(bezierrg);
3574 if (easyeasy && easyeasy.length == 5) {
3575 var curve = easyeasy;
3576 easyeasy = function (t) {
3577 return CubicBezierAtTime(t, +curve[1], +curve[2], +curve[3], +curve[4], ms);
3583 timestamp = params.start || anim.start || +new Date;
3587 timestamp: timestamp,
3588 start: timestamp + (anim.del || 0),
3590 initstatus: status || 0,
3598 callback: params.callback,
3601 repeat: times || anim.times,
3602 origin: element.attr(),
3603 totalOrigin: totalOrigin
3605 animationElements.push(e);
3606 if (status && !isInAnim) {
3608 e.start = new Date - ms * status;
3609 if (animationElements.length == 1) {
3613 animationElements.length == 1 && requestAnimFrame(animation);
3615 isInAnim.initstatus = status;
3616 isInAnim.start = new Date - isInAnim.ms * status;
3618 eve("anim.start." + element.id, element, anim);
3624 * Creates an animation object that can be passed to the @Element.animate or @Element.animateWith methods.
3625 * See also @Animation.delay and @Animation.repeat methods.
3629 - params (object) final attributes for the element, see also @Element.attr
3630 - ms (number) number of milliseconds for animation to run
3631 - easing (string) #optional easing type. Accept one of @Raphael.easing_formulas or CSS format: `cubic‐bezier(XX, XX, XX, XX)`
3632 - callback (function) #optional callback function. Will be called at the end of animation.
3634 = (object) @Animation
3636 R.animation = function (params, ms, easing, callback) {
3637 if (R.is(easing, "function") || !easing) {
3638 callback = callback || easing || null;
3641 params = Object(params);
3646 for (attr in params) if (params[has](attr) && toFloat(attr) != attr) {
3648 p[attr] = params[attr];
3651 return new Animation(params, ms);
3653 easing && (p.easing = easing);
3654 callback && (p.callback = callback);
3655 return new Animation({100: p}, ms);
3662 * Creates and starts animation for given element.
3666 - params (object) final attributes for the element, see also @Element.attr
3667 - ms (number) number of milliseconds for animation to run
3668 - easing (string) #optional easing type. Accept one of @Raphael.easing_formulas or CSS format: `cubic‐bezier(XX, XX, XX, XX)`
3669 - callback (function) #optional callback function. Will be called at the end of animation.
3671 - animation (object) animation object, see @Raphael.animation
3673 = (object) original element
3675 elproto.animate = function (params, ms, easing, callback) {
3677 if (element.removed) {
3678 callback && callback.call(element);
3681 var anim = params instanceof Animation ? params : R.animation(params, ms, easing, callback);
3682 runAnimation(anim, element, anim.percents[0], null, element.attr());
3689 * Sets the status of animation of the element in milliseconds. Similar to @Element.status method.
3693 - anim (object) animation object
3694 - value (number) number of milliseconds from the beginning of the animation
3696 = (object) original element if `value` is specified
3697 * Note, that during animation following events are triggered:
3699 * On each animation frame event `anim.frame.<id>`, on start `anim.start.<id>` and on end `anim.finish.<id>`.
3701 elproto.setTime = function (anim, value) {
3702 if (anim && value != null) {
3703 this.status(anim, mmin(value, anim.ms) / anim.ms);
3711 * Gets or sets the status of animation of the element.
3715 - anim (object) #optional animation object
3716 - 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.
3720 = (array) status if `anim` is not specified. Array of objects in format:
3722 o anim: (object) animation object
3723 o status: (number) status
3726 = (object) original element if `value` is specified
3728 elproto.status = function (anim, value) {
3733 if (value != null) {
3734 runAnimation(anim, this, -1, mmin(value, 1));
3737 len = animationElements.length;
3738 for (; i < len; i++) {
3739 e = animationElements[i];
3740 if (e.el.id == this.id && (!anim || e.anim == anim)) {
3744 out.push({anim: e.anim, status: e.status});
3757 * Stops animation of the element with ability to resume it later on.
3761 - anim (object) #optional animation object
3763 = (object) original element
3765 elproto.pause = function (anim) {
3766 for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) {
3767 if (eve("anim.pause." + this.id, this, animationElements[i].anim) !== false) {
3768 animationElements[i].paused = true;
3777 * Resumes animation if it was paused with @Element.pause method.
3781 - anim (object) #optional animation object
3783 = (object) original element
3785 elproto.resume = function (anim) {
3786 for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) {
3787 var e = animationElements[i];
3788 if (eve("anim.resume." + this.id, this, e.anim) !== false) {
3790 this.status(e.anim, e.status);
3799 * Stops animation of the element.
3803 - anim (object) #optional animation object
3805 = (object) original element
3807 elproto.stop = function (anim) {
3808 for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) {
3809 if (eve("anim.stop." + this.id, this, animationElements[i].anim) !== false) {
3810 animationElements.splice(i--, 1);
3815 elproto.toString = function () {
3816 return "Rapha\xebl\u2019s object";
3820 var Set = function (items) {
3825 for (var i = 0, ii = items.length; i < ii; i++) {
3826 if (items[i] && (items[i].constructor == elproto.constructor || items[i].constructor == Set)) {
3827 this[this.items.length] = this.items[this.items.length] = items[i];
3833 setproto = Set.prototype;
3838 * Adds each argument to the current set.
3839 = (object) original element
3841 setproto.push = function () {
3844 for (var i = 0, ii = arguments.length; i < ii; i++) {
3845 item = arguments[i];
3846 if (item && (item.constructor == elproto.constructor || item.constructor == Set)) {
3847 len = this.items.length;
3848 this[len] = this.items[len] = item;
3858 * Removes last element and returns it.
3861 setproto.pop = function () {
3862 this.length && delete this[this.length--];
3863 return this.items.pop();
3869 * Executes given function for each element in the set.
3871 * If function returns `false` it will stop loop running.
3875 - callback (function) function to run
3876 - thisArg (object) context object for the callback
3877 = (object) Set object
3879 setproto.forEach = function (callback, thisArg) {
3880 for (var i = 0, ii = this.items.length; i < ii; i++) {
3881 if (callback.call(thisArg, this.items[i]) === false) {
3887 for (var method in elproto) if (elproto[has](method)) {
3888 setproto[method] = (function (methodname) {
3889 return function () {
3890 var arg = arguments;
3891 return this.forEach(function (el) {
3892 el[methodname][apply](el, arg);
3897 setproto.attr = function (name, value) {
3898 if (name && R.is(name, array) && R.is(name[0], "object")) {
3899 for (var j = 0, jj = name.length; j < jj; j++) {
3900 this.items[j].attr(name[j]);
3903 for (var i = 0, ii = this.items.length; i < ii; i++) {
3904 this.items[i].attr(name, value);
3909 setproto.clear = function () {
3910 while (this.length) {
3914 setproto.animate = function (params, ms, easing, callback) {
3915 (R.is(easing, "function") || !easing) && (callback = easing || null);
3916 var len = this.items.length,
3924 callback && (collector = function () {
3925 !--len && callback.call(set);
3927 easing = R.is(easing, string) ? easing : collector;
3928 var anim = params instanceof Animation ? params : R.animation(params, ms, easing, collector);
3929 item = this.items[--i].animate(anim);
3931 this.items[i] && !this.items[i].removed && this.items[i].animateWith(item, anim);
3935 setproto.insertAfter = function (el) {
3936 var i = this.items.length;
3938 this.items[i].insertAfter(el);
3942 setproto.getBBox = function () {
3947 for (var i = this.items.length; i--;) if (!this.items[i].removed) {
3948 var box = this.items[i].getBBox();
3951 w.push(box.x + box.width);
3952 h.push(box.y + box.height);
3954 x = mmin[apply](0, x);
3955 y = mmin[apply](0, y);
3959 width: mmax[apply](0, w) - x,
3960 height: mmax[apply](0, h) - y
3963 setproto.clone = function (s) {
3965 for (var i = 0, ii = this.items.length; i < ii; i++) {
3966 s.push(this.items[i].clone());
3970 setproto.toString = function () {
3971 return "Rapha\xebl\u2018s set";
3974 R.registerFont = function (font) {
3978 this.fonts = this.fonts || {};
3984 family = font.face["font-family"];
3985 for (var prop in font.face) if (font.face[has](prop)) {
3986 fontcopy.face[prop] = font.face[prop];
3988 if (this.fonts[family]) {
3989 this.fonts[family].push(fontcopy);
3991 this.fonts[family] = [fontcopy];
3994 fontcopy.face["units-per-em"] = toInt(font.face["units-per-em"], 10);
3995 for (var glyph in font.glyphs) if (font.glyphs[has](glyph)) {
3996 var path = font.glyphs[glyph];
3997 fontcopy.glyphs[glyph] = {
4000 d: path.d && "M" + path.d.replace(/[mlcxtrv]/g, function (command) {
4001 return {l: "L", c: "C", x: "z", t: "m", r: "l", v: "c"}[command] || "M";
4005 for (var k in path.k) if (path[has](k)) {
4006 fontcopy.glyphs[glyph].k[k] = path.k[k];
4013 paperproto.getFont = function (family, weight, style, stretch) {
4014 stretch = stretch || "normal";
4015 style = style || "normal";
4016 weight = +weight || {normal: 400, bold: 700, lighter: 300, bolder: 800}[weight] || 400;
4020 var font = R.fonts[family];
4022 var name = new RegExp("(^|\\s)" + family.replace(/[^\w\d\s+!~.:_-]/g, E) + "(\\s|$)", "i");
4023 for (var fontName in R.fonts) if (R.fonts[has](fontName)) {
4024 if (name.test(fontName)) {
4025 font = R.fonts[fontName];
4032 for (var i = 0, ii = font.length; i < ii; i++) {
4034 if (thefont.face["font-weight"] == weight && (thefont.face["font-style"] == style || !thefont.face["font-style"]) && thefont.face["font-stretch"] == stretch) {
4041 paperproto.print = function (x, y, string, font, size, origin, letter_spacing) {
4042 origin = origin || "middle"; // baseline|middle
4043 letter_spacing = mmax(mmin(letter_spacing || 0, 1), -1);
4044 var out = this.set(),
4045 letters = Str(string).split(E),
4049 R.is(font, string) && (font = this.getFont(font));
4051 scale = (size || 16) / font.face["units-per-em"];
4052 var bb = font.face.bbox.split(separator),
4054 height = +bb[1] + (origin == "baseline" ? bb[3] - bb[1] + (+font.face.descent) : (bb[3] - bb[1]) / 2);
4055 for (var i = 0, ii = letters.length; i < ii; i++) {
4056 var prev = i && font.glyphs[letters[i - 1]] || {},
4057 curr = font.glyphs[letters[i]];
4058 shift += i ? (prev.w || font.w) + (prev.k && prev.k[letters[i]] || 0) + (font.w * letter_spacing) : 0;
4059 curr && curr.d && out.push(this.path(curr.d).attr({
4062 transform: [["t", shift * scale, 0]]
4065 out.transform(["...s", scale, scale, top, height, "t", (x - top) / scale, (y - height) / scale]);
4074 * Simple format function. Replaces construction of type “`{<number>}`” to the corresponding argument.
4078 - token (string) string to format
4079 - … (string) rest of arguments will be treated as parameters for replacement
4080 = (string) formated string
4086 | // this will draw a rectangular shape equivalent to "M10,20h40v50h-40z"
4087 | paper.path(Raphael.format("M{1},{2}h{3}v{4}h{5}z", x, y, width, height, -width));
4089 R.format = function (token, params) {
4090 var args = R.is(params, array) ? [0][concat](params) : arguments;
4091 token && R.is(token, string) && args.length - 1 && (token = token.replace(formatrg, function (str, i) {
4092 return args[++i] == null ? E : args[i];
4100 * A little bit more advanced format function than @Raphael.format. Replaces construction of type “`{<name>}`” to the corresponding argument.
4104 - token (string) string to format
4105 - json (object) object which properties will be used as a replacement
4106 = (string) formated string
4108 | // this will draw a rectangular shape equivalent to "M10,20h40v50h-40z"
4109 | paper.path(Raphael.format("M{x},{y}h{dim.width}v{dim.height}h{dim['negative width']}z", {
4115 | "negative width": -40
4119 R.fullfill = (function () {
4120 var tokenRegex = /\{([^\}]+)\}/g,
4121 objNotationRegex = /(?:(?:^|\.)(.+?)(?=\[|\.|$|\()|\[('|")(.+?)\2\])(\(\))?/g, // matches .xxxxx or ["xxxxx"] to run over object properties
4122 replacer = function (all, key, obj) {
4124 key.replace(objNotationRegex, function (all, name, quote, quotedName, isFunc) {
4125 name = name || quotedName;
4130 typeof res == "function" && isFunc && (res = res());
4133 res = (res == null || res == obj ? all : res) + "";
4136 return function (str, obj) {
4137 return String(str).replace(tokenRegex, function (all, key) {
4138 return replacer(all, key, obj);
4146 * 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.
4147 * Beware, that in this case plugins could stop working, because they are depending on global variable existance.
4149 = (object) Raphael object
4151 | (function (local_raphael) {
4152 | var paper = local_raphael(10, 10, 320, 200);
4154 | })(Raphael.ninja());
4156 R.ninja = function () {
4157 oldRaphael.was ? (g.win.Raphael = oldRaphael.is) : delete Raphael;
4162 [ property (object) ]
4164 * You can add your own method to elements and sets. It is wise to add a set method for each element method
4165 * you added, so you will be able to call the same method on sets too.
4167 * See also @Raphael.el.
4169 | Raphael.el.red = function () {
4170 | this.attr({fill: "#f00"});
4172 | Raphael.st.red = function () {
4173 | this.forEach(function () {
4178 | paper.set(paper.circle(100, 100, 20), paper.circle(110, 100, 20)).red();
4181 // Firefox <3.6 fix: http://webreflection.blogspot.com/2009/11/195-chars-to-help-lazy-loading.html
4182 (function (doc, loaded, f) {
4183 if (doc.readyState == null && doc.addEventListener){
4184 doc.addEventListener(loaded, f = function () {
4185 doc.removeEventListener(loaded, f, false);
4186 doc.readyState = "complete";
4188 doc.readyState = "loading";
4190 function isLoaded() {
4191 (/in/).test(doc.readyState) ? setTimeout(isLoaded, 9) : R.eve("DOMload");
4194 })(document, "DOMContentLoaded");
4196 oldRaphael.was ? (g.win.Raphael = R) : (Raphael = R);
4198 eve.on("DOMload", function () {