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 () {
105 [ property (object) ]
107 * Shortcut for @Paper.customAttributes
110 * Paper.customAttributes
111 [ property (object) ]
113 * If you have a set of attributes that you would like to represent
114 * as a function of some number you can do it easily with custom attributes:
116 | paper.customAttributes.hue = function (num) {
118 | return {fill: "hsb(" + num + ", 0.75, 1)"};
120 | // Custom attribute “hue” will change fill
121 | // to be given hue with fixed saturation and brightness.
122 | // Now you can use it like this:
123 | var c = paper.circle(10, 10, 10).attr({hue: .45});
124 | // or even like this:
125 | c.animate({hue: 1}, 1e3);
127 | // You could also create custom attribute
128 | // with multiple parameters:
129 | paper.customAttributes.hsb = function (h, s, b) {
130 | return {fill: "hsb(" + [h, s, b].join(",") + ")"};
132 | c.attr({hsb: "0.5 .8 1"});
133 | c.animate({hsb: [1, 0, 0.5]}, 1e3);
135 this.ca = this.customAttributes = {};
138 appendChild = "appendChild",
141 supportsTouch = "createTouch" in g.doc,
146 events = "click dblclick mousedown mousemove mouseout mouseover mouseup touchstart touchmove touchend touchcancel"[split](S),
148 mousedown: "touchstart",
149 mousemove: "touchmove",
152 lowerCase = Str.prototype.toLowerCase,
162 toString = "toString",
164 objectToString = Object.prototype.toString,
167 ISURL = R._ISURL = /^url\(['"]?([^\)]+?)['"]?\)$/i,
168 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,
169 isnan = {"NaN": 1, "Infinity": 1, "-Infinity": 1},
170 bezierrg = /^(?:cubic-)?bezier\(([^,]+),([^,]+),([^,]+),([^\)]+)\)/,
172 setAttribute = "setAttribute",
173 toFloat = parseFloat,
175 upperCase = Str.prototype.toUpperCase,
176 availableAttrs = R._availableAttrs = {
178 "arrow-start": "none",
180 "clip-rect": "0 0 1e9 1e9",
186 font: '10px "Arial"',
187 "font-family": '"Arial"',
189 "font-style": "normal",
193 href: "http://raphaeljs.com/",
201 "stroke-dasharray": "",
202 "stroke-linecap": "butt",
203 "stroke-linejoin": "butt",
204 "stroke-miterlimit": 0,
208 "text-anchor": "middle",
215 availableAnimAttrs = R._availableAnimAttrs = {
230 "stroke-opacity": nu,
232 transform: "transform",
237 commaSpaces = /\s*,\s*/,
238 hsrg = {hs: 1, rg: 1},
239 p2s = /,?([achlmqrstvxz]),?/gi,
240 pathCommand = /([achlmrqstvz])[\s,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?\s*,?\s*)+)/ig,
241 tCommand = /([rstm])[\s,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?\s*,?\s*)+)/ig,
242 pathValues = /(-?\d*\.?\d*(?:e[\-+]?\d+)?)\s*,?\s*/ig,
243 radial_gradient = R._radial_gradient = /^r(?:\(([^,]+?)\s*,\s*([^\)]+?)\))?/,
245 sortByKey = function (a, b) {
246 return a.key - b.key;
248 sortByNumber = function (a, b) {
249 return toFloat(a) - toFloat(b);
251 fun = function () {},
252 pipe = function (x) {
255 rectPath = R._rectPath = function (x, y, w, h, r) {
257 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"]];
259 return [["M", x, y], ["l", w, 0], ["l", 0, h], ["l", -w, 0], ["z"]];
261 ellipsePath = function (x, y, rx, ry) {
265 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"]];
267 getPath = R._getPath = {
268 path: function (el) {
269 return el.attr("path");
271 circle: function (el) {
273 return ellipsePath(a.cx, a.cy, a.r);
275 ellipse: function (el) {
277 return ellipsePath(a.cx, a.cy, a.rx, a.ry);
279 rect: function (el) {
281 return rectPath(a.x, a.y, a.width, a.height, a.r);
283 image: function (el) {
285 return rectPath(a.x, a.y, a.width, a.height);
287 text: function (el) {
288 var bbox = el._getBBox();
289 return rectPath(bbox.x, bbox.y, bbox.width, bbox.height);
292 mapPath = R.mapPath = function (path, matrix) {
296 var x, y, i, j, pathi;
297 path = path2curve(path);
298 for (i = 0, ii = path.length; i < ii; i++) {
300 for (j = 1, jj = pathi.length; j < jj; j += 2) {
301 x = matrix.x(pathi[j], pathi[j + 1]);
302 y = matrix.y(pathi[j], pathi[j + 1]);
313 [ property (string) ]
315 * Can be “SVG”, “VML” or empty, depending on browser support.
317 R.type = (g.win.SVGAngle || g.doc.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") ? "SVG" : "VML");
318 if (R.type == "VML") {
319 var d = g.doc.createElement("div"),
321 d.innerHTML = '<v:shape adj="1"/>';
323 b.style.behavior = "url(#default#VML)";
324 if (!(b && typeof b.adj == "object")) {
331 [ property (boolean) ]
333 * `true` if browser supports SVG.
337 [ property (boolean) ]
339 * `true` if browser supports VML.
341 R.svg = !(R.vml = R.type == "VML");
345 [ property (object) ]
347 * You can add your own method to the canvas. For example if you want to draw a pie chart,
348 * you can create your own pie chart function and ship it as a Raphaël plugin. To do this
349 * you need to extend the `Raphael.fn` object. You should modify the `fn` object before a
350 * Raphaël instance is created, otherwise it will take no effect. Please note that the
351 * ability for namespaced plugins was removed in Raphael 2.0. It is up to the plugin to
352 * ensure any namespacing ensures proper context.
354 | Raphael.fn.arrow = function (x1, y1, x2, y2, size) {
355 | return this.path( ... );
357 | // or create namespace
358 | Raphael.fn.mystuff = {
359 | arrow: function () {…},
360 | star: function () {…},
363 | var paper = Raphael(10, 10, 630, 480);
365 | paper.arrow(10, 10, 30, 30, 5).attr({fill: "#f00"});
366 | paper.mystuff.arrow();
367 | paper.mystuff.star();
369 R.fn = paperproto = Paper.prototype = R.prototype;
376 * Handfull replacement for `typeof` operator.
378 - o (…) any object or primitive
379 - type (string) name of the type, i.e. “string”, “function”, “number”, etc.
380 = (boolean) is given value is of given type
382 R.is = function (o, type) {
383 type = lowerCase.call(type);
384 if (type == "finite") {
385 return !isnan[has](+o);
387 if (type == "array") {
388 return o instanceof Array;
390 return (type == "null" && o === null) ||
391 (type == typeof o && o !== null) ||
392 (type == "object" && o === Object(o)) ||
393 (type == "array" && Array.isArray && Array.isArray(o)) ||
394 objectToString.call(o).slice(8, -1).toLowerCase() == type;
400 * Returns angle between two or three points
402 - x1 (number) x coord of first point
403 - y1 (number) y coord of first point
404 - x2 (number) x coord of second point
405 - y2 (number) y coord of second point
406 - x3 (number) #optional x coord of third point
407 - y3 (number) #optional y coord of third point
408 = (number) angle in degrees.
410 R.angle = function (x1, y1, x2, y2, x3, y3) {
417 return (180 + math.atan2(-y, -x) * 180 / PI + 360) % 360;
419 return R.angle(x1, y1, x3, y3) - R.angle(x2, y2, x3, y3);
426 * Transform angle to radians
428 - deg (number) angle in degrees
429 = (number) angle in radians.
431 R.rad = function (deg) {
432 return deg % 360 * PI / 180;
438 * Transform angle to degrees
440 - deg (number) angle in radians
441 = (number) angle in degrees.
443 R.deg = function (rad) {
444 return rad * 180 / PI % 360;
450 * Snaps given value to given grid.
452 - values (array|number) given array of values or step of the grid
453 - value (number) value to adjust
454 - tolerance (number) #optional tolerance for snapping. Default is `10`.
455 = (number) adjusted value.
457 R.snapTo = function (values, value, tolerance) {
458 tolerance = R.is(tolerance, "finite") ? tolerance : 10;
459 if (R.is(values, array)) {
460 var i = values.length;
461 while (i--) if (abs(values[i] - value) <= tolerance) {
466 var rem = value % values;
467 if (rem < tolerance) {
470 if (rem > values - tolerance) {
471 return value - rem + values;
481 * Returns RFC4122, version 4 ID
483 var createUUID = R.createUUID = (function (uuidRegEx, uuidReplacer) {
485 return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(uuidRegEx, uuidReplacer).toUpperCase();
487 })(/[xy]/g, function (c) {
488 var r = math.random() * 16 | 0,
489 v = c == "x" ? r : (r & 3 | 8);
490 return v.toString(16);
497 * Used when you need to draw in `<iframe>`. Switched window to the iframe one.
499 - newwin (window) new window object
501 R.setWindow = function (newwin) {
502 eve("setWindow", R, g.win, newwin);
504 g.doc = g.win.document;
509 var toHex = function (color) {
511 // http://dean.edwards.name/weblog/2009/10/convert-any-colour-value-to-hex-in-msie/
512 var trim = /^\s+|\s+$/g;
515 var docum = new ActiveXObject("htmlfile");
516 docum.write("<body>");
520 bod = createPopup().document.body;
522 var range = bod.createTextRange();
523 toHex = cacher(function (color) {
525 bod.style.color = Str(color).replace(trim, E);
526 var value = range.queryCommandValue("ForeColor");
527 value = ((value & 255) << 16) | (value & 65280) | ((value & 16711680) >>> 16);
528 return "#" + ("000000" + value.toString(16)).slice(-6);
534 var i = g.doc.createElement("i");
535 i.title = "Rapha\xebl Colour Picker";
536 i.style.display = "none";
537 g.doc.body.appendChild(i);
538 toHex = cacher(function (color) {
539 i.style.color = color;
540 return g.doc.defaultView.getComputedStyle(i, E).getPropertyValue("color");
545 hsbtoString = function () {
546 return "hsb(" + [this.h, this.s, this.b] + ")";
548 hsltoString = function () {
549 return "hsl(" + [this.h, this.s, this.l] + ")";
551 rgbtoString = function () {
554 prepareRGB = function (r, g, b) {
555 if (g == null && R.is(r, "object") && "r" in r && "g" in r && "b" in r) {
560 if (g == null && R.is(r, string)) {
561 var clr = R.getRGB(r);
566 if (r > 1 || g > 1 || b > 1) {
574 packageRGB = function (r, g, b, o) {
583 toString: rgbtoString
585 R.is(o, "finite") && (rgb.opacity = o);
593 * Parses the color string and returns object with all values for the given color.
595 - clr (string) color string in one of the supported formats (see @Raphael.getRGB)
596 = (object) Combined RGB & HSB object in format:
601 o hex (string) color in HTML/CSS format: #••••••,
602 o error (boolean) `true` if string can’t be parsed,
604 o s (number) saturation,
605 o v (number) value (brightness),
606 o l (number) lightness
609 R.color = function (clr) {
611 if (R.is(clr, "object") && "h" in clr && "s" in clr && "b" in clr) {
612 rgb = R.hsb2rgb(clr);
617 } else if (R.is(clr, "object") && "h" in clr && "s" in clr && "l" in clr) {
618 rgb = R.hsl2rgb(clr);
624 if (R.is(clr, "string")) {
627 if (R.is(clr, "object") && "r" in clr && "g" in clr && "b" in clr) {
628 rgb = R.rgb2hsl(clr);
632 rgb = R.rgb2hsb(clr);
636 crl.r = clr.g = clr.b = clr.h = clr.s = clr.v = clr.l = -1;
639 clr.toString = rgbtoString;
646 * Converts HSB values to RGB object.
649 - s (number) saturation
650 - v (number) value or brightness
651 = (object) RGB object in format:
656 o hex (string) color in HTML/CSS format: #••••••
659 R.hsb2rgb = function (h, s, v, o) {
660 if (this.is(h, "object") && "h" in h && "s" in h && "b" in h) {
670 X = C * (1 - abs(h % 2 - 1));
674 R += [C, X, 0, 0, X, C][h];
675 G += [X, C, C, X, 0, 0][h];
676 B += [0, 0, X, C, C, X][h];
677 return packageRGB(R, G, B, o);
683 * Converts HSL values to RGB object.
686 - s (number) saturation
687 - l (number) luminosity
688 = (object) RGB object in format:
693 o hex (string) color in HTML/CSS format: #••••••
696 R.hsl2rgb = function (h, s, l, o) {
697 if (this.is(h, "object") && "h" in h && "s" in h && "l" in h) {
702 if (h > 1 || s > 1 || l > 1) {
710 C = 2 * s * (l < .5 ? l : 1 - l);
711 X = C * (1 - abs(h % 2 - 1));
712 R = G = B = l - C / 2;
715 R += [C, X, 0, 0, X, C][h];
716 G += [X, C, C, X, 0, 0][h];
717 B += [0, 0, X, C, C, X][h];
718 return packageRGB(R, G, B, o);
724 * Converts RGB values to HSB object.
729 = (object) HSB object in format:
732 o s (number) saturation
733 o b (number) brightness
736 R.rgb2hsb = function (r, g, b) {
737 b = prepareRGB(r, g, b);
744 C = V - mmin(r, g, b);
746 V == r ? (g - b) / C :
747 V == g ? (b - r) / C + 2 :
750 H = ((H + 360) % 6) * 60 / 360;
751 S = C == 0 ? 0 : C / V;
752 return {h: H, s: S, b: V, toString: hsbtoString};
758 * Converts RGB values to HSL object.
763 = (object) HSL object in format:
766 o s (number) saturation
767 o l (number) luminosity
770 R.rgb2hsl = function (r, g, b) {
771 b = prepareRGB(r, g, b);
776 var H, S, L, M, m, C;
781 M == r ? (g - b) / C :
782 M == g ? (b - r) / C + 2 :
784 H = ((H + 360) % 6) * 60 / 360;
787 L < .5 ? C / (2 * L) :
789 return {h: H, s: S, l: L, toString: hsltoString};
791 R._path2string = function () {
792 return this.join(",").replace(p2s, "$1");
794 function repush(array, item) {
795 for (var i = 0, ii = array.length; i < ii; i++) if (array[i] === item) {
796 return array.push(array.splice(i, 1)[0]);
799 function cacher(f, scope, postprocessor) {
801 var arg = Array.prototype.slice.call(arguments, 0),
802 args = arg.join("\u2400"),
803 cache = newf.cache = newf.cache || {},
804 count = newf.count = newf.count || [];
805 if (cache[has](args)) {
807 return postprocessor ? postprocessor(cache[args]) : cache[args];
809 count.length >= 1e3 && delete cache[count.shift()];
811 cache[args] = f[apply](scope, arg);
812 return postprocessor ? postprocessor(cache[args]) : cache[args];
817 var preload = R._preload = function (src, f) {
818 var img = g.doc.createElement("img");
819 img.style.cssText = "position:absolute;left:-9999em;top-9999em";
820 img.onload = function () {
823 g.doc.body.removeChild(this);
825 img.onerror = function () {
826 g.doc.body.removeChild(this);
828 g.doc.body.appendChild(img);
832 function clrToString() {
840 * Parses colour string as RGB object
842 - colour (string) colour string in one of formats:
844 # <li>Colour name (“<code>red</code>”, “<code>green</code>”, “<code>cornflowerblue</code>”, etc)</li>
845 # <li>#••• — shortened HTML colour: (“<code>#000</code>”, “<code>#fc0</code>”, etc)</li>
846 # <li>#•••••• — full length HTML colour: (“<code>#000000</code>”, “<code>#bd2300</code>”)</li>
847 # <li>rgb(•••, •••, •••) — red, green and blue channels’ values: (“<code>rgb(200, 100, 0)</code>”)</li>
848 # <li>rgb(•••%, •••%, •••%) — same as above, but in %: (“<code>rgb(100%, 175%, 0%)</code>”)</li>
849 # <li>hsb(•••, •••, •••) — hue, saturation and brightness values: (“<code>hsb(0.5, 0.25, 1)</code>”)</li>
850 # <li>hsb(•••%, •••%, •••%) — same as above, but in %</li>
851 # <li>hsl(•••, •••, •••) — same as hsb</li>
852 # <li>hsl(•••%, •••%, •••%) — same as hsb</li>
854 = (object) RGB object in format:
859 o hex (string) color in HTML/CSS format: #••••••,
860 o error (boolean) true if string can’t be parsed
863 R.getRGB = cacher(function (colour) {
864 if (!colour || !!((colour = Str(colour)).indexOf("-") + 1)) {
865 return {r: -1, g: -1, b: -1, hex: "none", error: 1, toString: clrToString};
867 if (colour == "none") {
868 return {r: -1, g: -1, b: -1, hex: "none", toString: clrToString};
870 !(hsrg[has](colour.toLowerCase().substring(0, 2)) || colour.charAt() == "#") && (colour = toHex(colour));
878 rgb = colour.match(colourRegExp);
881 blue = toInt(rgb[2].substring(5), 16);
882 green = toInt(rgb[2].substring(3, 5), 16);
883 red = toInt(rgb[2].substring(1, 3), 16);
886 blue = toInt((t = rgb[3].charAt(3)) + t, 16);
887 green = toInt((t = rgb[3].charAt(2)) + t, 16);
888 red = toInt((t = rgb[3].charAt(1)) + t, 16);
891 values = rgb[4][split](commaSpaces);
892 red = toFloat(values[0]);
893 values[0].slice(-1) == "%" && (red *= 2.55);
894 green = toFloat(values[1]);
895 values[1].slice(-1) == "%" && (green *= 2.55);
896 blue = toFloat(values[2]);
897 values[2].slice(-1) == "%" && (blue *= 2.55);
898 rgb[1].toLowerCase().slice(0, 4) == "rgba" && (opacity = toFloat(values[3]));
899 values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
902 values = rgb[5][split](commaSpaces);
903 red = toFloat(values[0]);
904 values[0].slice(-1) == "%" && (red *= 2.55);
905 green = toFloat(values[1]);
906 values[1].slice(-1) == "%" && (green *= 2.55);
907 blue = toFloat(values[2]);
908 values[2].slice(-1) == "%" && (blue *= 2.55);
909 (values[0].slice(-3) == "deg" || values[0].slice(-1) == "\xb0") && (red /= 360);
910 rgb[1].toLowerCase().slice(0, 4) == "hsba" && (opacity = toFloat(values[3]));
911 values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
912 return R.hsb2rgb(red, green, blue, opacity);
915 values = rgb[6][split](commaSpaces);
916 red = toFloat(values[0]);
917 values[0].slice(-1) == "%" && (red *= 2.55);
918 green = toFloat(values[1]);
919 values[1].slice(-1) == "%" && (green *= 2.55);
920 blue = toFloat(values[2]);
921 values[2].slice(-1) == "%" && (blue *= 2.55);
922 (values[0].slice(-3) == "deg" || values[0].slice(-1) == "\xb0") && (red /= 360);
923 rgb[1].toLowerCase().slice(0, 4) == "hsla" && (opacity = toFloat(values[3]));
924 values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
925 return R.hsl2rgb(red, green, blue, opacity);
927 rgb = {r: red, g: green, b: blue, toString: clrToString};
928 rgb.hex = "#" + (16777216 | blue | (green << 8) | (red << 16)).toString(16).slice(1);
929 R.is(opacity, "finite") && (rgb.opacity = opacity);
932 return {r: -1, g: -1, b: -1, hex: "none", error: 1, toString: clrToString};
938 * Converts HSB values to hex representation of the colour.
941 - s (number) saturation
942 - b (number) value or brightness
943 = (string) hex representation of the colour.
945 R.hsb = cacher(function (h, s, b) {
946 return R.hsb2rgb(h, s, b).hex;
952 * Converts HSL values to hex representation of the colour.
955 - s (number) saturation
956 - l (number) luminosity
957 = (string) hex representation of the colour.
959 R.hsl = cacher(function (h, s, l) {
960 return R.hsl2rgb(h, s, l).hex;
966 * Converts RGB values to hex representation of the colour.
971 = (string) hex representation of the colour.
973 R.rgb = cacher(function (r, g, b) {
974 return "#" + (16777216 | b | (g << 8) | (r << 16)).toString(16).slice(1);
980 * On each call returns next colour in the spectrum. To reset it back to red call @Raphael.getColor.reset
982 - value (number) #optional brightness, default is `0.75`
983 = (string) hex representation of the colour.
985 R.getColor = function (value) {
986 var start = this.getColor.start = this.getColor.start || {h: 0, s: 1, b: value || .75},
987 rgb = this.hsb2rgb(start.h, start.s, start.b);
992 start.s <= 0 && (this.getColor.start = {h: 0, s: 1, b: start.b});
997 * Raphael.getColor.reset
1000 * Resets spectrum position for @Raphael.getColor back to red.
1002 R.getColor.reset = function () {
1006 // http://schepers.cc/getting-to-the-point
1007 function catmullRom2bezier(crp) {
1009 for (var i = 0, iLen = crp.length; iLen - 2 > i; i += 2) {
1010 var p = [{x: +crp[i], y: +crp[i + 1]},
1011 {x: +crp[i], y: +crp[i + 1]},
1012 {x: +crp[i + 2], y: +crp[i + 3]},
1013 {x: +crp[i + 4], y: +crp[i + 5]}];
1014 if (iLen - 4 == i) {
1015 p[0] = {x: +crp[i - 2], y: +crp[i - 1]};
1018 p[0] = {x: +crp[i - 2], y: +crp[i - 1]};
1021 (-p[0].x + 6 * p[1].x + p[2].x) / 6,
1022 (-p[0].y + 6 * p[1].y + p[2].y) / 6,
1023 (p[1].x + 6 * p[2].x - p[3].x) / 6,
1024 (p[1].y + 6*p[2].y - p[3].y) / 6,
1033 * Raphael.parsePathString
1038 * Parses given path string into an array of arrays of path segments.
1040 - pathString (string|array) path string or array of segments (in the last case it will be returned straight away)
1041 = (array) array of segments.
1043 R.parsePathString = cacher(function (pathString) {
1047 var paramCounts = {a: 7, c: 6, h: 1, l: 2, m: 2, r: 4, q: 4, s: 4, t: 2, v: 1, z: 0},
1049 if (R.is(pathString, array) && R.is(pathString[0], array)) { // rough assumption
1050 data = pathClone(pathString);
1053 Str(pathString).replace(pathCommand, function (a, b, c) {
1055 name = b.toLowerCase();
1056 c.replace(pathValues, function (a, b) {
1057 b && params.push(+b);
1059 if (name == "m" && params.length > 2) {
1060 data.push([b][concat](params.splice(0, 2)));
1062 b = b == "m" ? "l" : "L";
1065 data.push([b][concat](params));
1066 } else while (params.length >= paramCounts[name]) {
1067 data.push([b][concat](params.splice(0, paramCounts[name])));
1068 if (!paramCounts[name]) {
1074 data.toString = R._path2string;
1078 * Raphael.parseTransformString
1083 * Parses given path string into an array of transformations.
1085 - TString (string|array) transform string or array of transformations (in the last case it will be returned straight away)
1086 = (array) array of transformations.
1088 R.parseTransformString = cacher(function (TString) {
1092 var paramCounts = {r: 3, s: 4, t: 2, m: 6},
1094 if (R.is(TString, array) && R.is(TString[0], array)) { // rough assumption
1095 data = pathClone(TString);
1098 Str(TString).replace(tCommand, function (a, b, c) {
1100 name = lowerCase.call(b);
1101 c.replace(pathValues, function (a, b) {
1102 b && params.push(+b);
1104 data.push([b][concat](params));
1107 data.toString = R._path2string;
1111 * Raphael.findDotsAtSegment
1116 * Find dot coordinates on the given cubic bezier curve at the given t.
1118 - p1x (number) x of the first point of the curve
1119 - p1y (number) y of the first point of the curve
1120 - c1x (number) x of the first anchor of the curve
1121 - c1y (number) y of the first anchor of the curve
1122 - c2x (number) x of the second anchor of the curve
1123 - c2y (number) y of the second anchor of the curve
1124 - p2x (number) x of the second point of the curve
1125 - p2y (number) y of the second point of the curve
1126 - t (number) position on the curve (0..1)
1127 = (object) point information in format:
1129 o x: (number) x coordinate of the point
1130 o y: (number) y coordinate of the point
1132 o x: (number) x coordinate of the left anchor
1133 o y: (number) y coordinate of the left anchor
1136 o x: (number) x coordinate of the right anchor
1137 o y: (number) y coordinate of the right anchor
1140 o x: (number) x coordinate of the start of the curve
1141 o y: (number) y coordinate of the start of the curve
1144 o x: (number) x coordinate of the end of the curve
1145 o y: (number) y coordinate of the end of the curve
1147 o alpha: (number) angle of the curve derivative at the point
1150 R.findDotsAtSegment = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) {
1156 x = t13 * p1x + t12 * 3 * t * c1x + t1 * 3 * t * t * c2x + t3 * p2x,
1157 y = t13 * p1y + t12 * 3 * t * c1y + t1 * 3 * t * t * c2y + t3 * p2y,
1158 mx = p1x + 2 * t * (c1x - p1x) + t2 * (c2x - 2 * c1x + p1x),
1159 my = p1y + 2 * t * (c1y - p1y) + t2 * (c2y - 2 * c1y + p1y),
1160 nx = c1x + 2 * t * (c2x - c1x) + t2 * (p2x - 2 * c2x + c1x),
1161 ny = c1y + 2 * t * (c2y - c1y) + t2 * (p2y - 2 * c2y + c1y),
1162 ax = t1 * p1x + t * c1x,
1163 ay = t1 * p1y + t * c1y,
1164 cx = t1 * c2x + t * p2x,
1165 cy = t1 * c2y + t * p2y,
1166 alpha = (90 - math.atan2(mx - nx, my - ny) * 180 / PI);
1167 (mx > nx || my < ny) && (alpha += 180);
1173 start: {x: ax, y: ay},
1174 end: {x: cx, y: cy},
1178 var pathDimensions = cacher(function (path) {
1180 return {x: 0, y: 0, width: 0, height: 0};
1182 path = path2curve(path);
1188 for (var i = 0, ii = path.length; i < ii; i++) {
1196 var dim = curveDim(x, y, p[1], p[2], p[3], p[4], p[5], p[6]);
1197 X = X[concat](dim.min.x, dim.max.x);
1198 Y = Y[concat](dim.min.y, dim.max.y);
1203 var xmin = mmin[apply](0, X),
1204 ymin = mmin[apply](0, Y);
1208 width: mmax[apply](0, X) - xmin,
1209 height: mmax[apply](0, Y) - ymin
1211 }, null, function (o) {
1219 pathClone = function (pathArray) {
1221 if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) { // rough assumption
1222 pathArray = R.parsePathString(pathArray);
1224 for (var i = 0, ii = pathArray.length; i < ii; i++) {
1226 for (var j = 0, jj = pathArray[i].length; j < jj; j++) {
1227 res[i][j] = pathArray[i][j];
1230 res.toString = R._path2string;
1233 pathToRelative = R._pathToRelative = cacher(function (pathArray) {
1234 if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) { // rough assumption
1235 pathArray = R.parsePathString(pathArray);
1243 if (pathArray[0][0] == "M") {
1244 x = pathArray[0][1];
1245 y = pathArray[0][2];
1249 res.push(["M", x, y]);
1251 for (var i = start, ii = pathArray.length; i < ii; i++) {
1252 var r = res[i] = [],
1254 if (pa[0] != lowerCase.call(pa[0])) {
1255 r[0] = lowerCase.call(pa[0]);
1263 r[6] = +(pa[6] - x).toFixed(3);
1264 r[7] = +(pa[7] - y).toFixed(3);
1267 r[1] = +(pa[1] - y).toFixed(3);
1273 for (var j = 1, jj = pa.length; j < jj; j++) {
1274 r[j] = +(pa[j] - ((j % 2) ? x : y)).toFixed(3);
1283 for (var k = 0, kk = pa.length; k < kk; k++) {
1287 var len = res[i].length;
1288 switch (res[i][0]) {
1294 x += +res[i][len - 1];
1297 y += +res[i][len - 1];
1300 x += +res[i][len - 2];
1301 y += +res[i][len - 1];
1304 res.toString = R._path2string;
1307 pathToAbsolute = R._pathToAbsolute = cacher(function (pathArray) {
1308 if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) { // rough assumption
1309 pathArray = R.parsePathString(pathArray);
1311 if (!pathArray || !pathArray.length) {
1312 return [["M", 0, 0]];
1320 if (pathArray[0][0] == "M") {
1321 x = +pathArray[0][1];
1322 y = +pathArray[0][2];
1326 res[0] = ["M", x, y];
1328 for (var r, pa, i = start, ii = pathArray.length; i < ii; i++) {
1331 if (pa[0] != upperCase.call(pa[0])) {
1332 r[0] = upperCase.call(pa[0]);
1340 r[6] = +(pa[6] + x);
1341 r[7] = +(pa[7] + y);
1350 var dots = [x, y][concat](pa.slice(1));
1351 for (var j = 2, jj = dots.length; j < jj; j++) {
1352 dots[j] = +dots[j] + x;
1353 dots[++j] = +dots[j] + y;
1356 res = res[concat](catmullRom2bezier(dots));
1362 for (j = 1, jj = pa.length; j < jj; j++) {
1363 r[j] = +pa[j] + ((j % 2) ? x : y);
1366 } else if (pa[0] == "R") {
1367 dots = [x, y][concat](pa.slice(1));
1369 res = res[concat](catmullRom2bezier(dots));
1370 r = ["R"][concat](pa.slice(-2));
1372 for (var k = 0, kk = pa.length; k < kk; k++) {
1388 mx = r[r.length - 2];
1389 my = r[r.length - 1];
1391 x = r[r.length - 2];
1392 y = r[r.length - 1];
1395 res.toString = R._path2string;
1397 }, null, pathClone),
1398 l2c = function (x1, y1, x2, y2) {
1399 return [x1, y1, x2, y2, x2, y2];
1401 q2c = function (x1, y1, ax, ay, x2, y2) {
1405 _13 * x1 + _23 * ax,
1406 _13 * y1 + _23 * ay,
1407 _13 * x2 + _23 * ax,
1408 _13 * y2 + _23 * ay,
1413 a2c = function (x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursive) {
1414 // for more information of where this math came from visit:
1415 // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
1416 var _120 = PI * 120 / 180,
1417 rad = PI / 180 * (+angle || 0),
1420 rotate = cacher(function (x, y, rad) {
1421 var X = x * math.cos(rad) - y * math.sin(rad),
1422 Y = x * math.sin(rad) + y * math.cos(rad);
1423 return {x: X, y: Y};
1426 xy = rotate(x1, y1, -rad);
1429 xy = rotate(x2, y2, -rad);
1432 var cos = math.cos(PI / 180 * angle),
1433 sin = math.sin(PI / 180 * angle),
1436 var h = (x * x) / (rx * rx) + (y * y) / (ry * ry);
1444 k = (large_arc_flag == sweep_flag ? -1 : 1) *
1445 math.sqrt(abs((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x))),
1446 cx = k * rx * y / ry + (x1 + x2) / 2,
1447 cy = k * -ry * x / rx + (y1 + y2) / 2,
1448 f1 = math.asin(((y1 - cy) / ry).toFixed(9)),
1449 f2 = math.asin(((y2 - cy) / ry).toFixed(9));
1451 f1 = x1 < cx ? PI - f1 : f1;
1452 f2 = x2 < cx ? PI - f2 : f2;
1453 f1 < 0 && (f1 = PI * 2 + f1);
1454 f2 < 0 && (f2 = PI * 2 + f2);
1455 if (sweep_flag && f1 > f2) {
1458 if (!sweep_flag && f2 > f1) {
1468 if (abs(df) > _120) {
1472 f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1);
1473 x2 = cx + rx * math.cos(f2);
1474 y2 = cy + ry * math.sin(f2);
1475 res = a2c(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [f2, f2old, cx, cy]);
1478 var c1 = math.cos(f1),
1482 t = math.tan(df / 4),
1483 hx = 4 / 3 * rx * t,
1484 hy = 4 / 3 * ry * t,
1486 m2 = [x1 + hx * s1, y1 - hy * c1],
1487 m3 = [x2 + hx * s2, y2 - hy * c2],
1489 m2[0] = 2 * m1[0] - m2[0];
1490 m2[1] = 2 * m1[1] - m2[1];
1492 return [m2, m3, m4][concat](res);
1494 res = [m2, m3, m4][concat](res).join()[split](",");
1496 for (var i = 0, ii = res.length; i < ii; i++) {
1497 newres[i] = i % 2 ? rotate(res[i - 1], res[i], rad).y : rotate(res[i], res[i + 1], rad).x;
1502 findDotAtSegment = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) {
1505 x: pow(t1, 3) * p1x + pow(t1, 2) * 3 * t * c1x + t1 * 3 * t * t * c2x + pow(t, 3) * p2x,
1506 y: pow(t1, 3) * p1y + pow(t1, 2) * 3 * t * c1y + t1 * 3 * t * t * c2y + pow(t, 3) * p2y
1509 curveDim = cacher(function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) {
1510 var a = (c2x - 2 * c1x + p1x) - (p2x - 2 * c2x + c1x),
1511 b = 2 * (c1x - p1x) - 2 * (c2x - c1x),
1513 t1 = (-b + math.sqrt(b * b - 4 * a * c)) / 2 / a,
1514 t2 = (-b - math.sqrt(b * b - 4 * a * c)) / 2 / a,
1518 abs(t1) > "1e12" && (t1 = .5);
1519 abs(t2) > "1e12" && (t2 = .5);
1520 if (t1 > 0 && t1 < 1) {
1521 dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t1);
1525 if (t2 > 0 && t2 < 1) {
1526 dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t2);
1530 a = (c2y - 2 * c1y + p1y) - (p2y - 2 * c2y + c1y);
1531 b = 2 * (c1y - p1y) - 2 * (c2y - c1y);
1533 t1 = (-b + math.sqrt(b * b - 4 * a * c)) / 2 / a;
1534 t2 = (-b - math.sqrt(b * b - 4 * a * c)) / 2 / a;
1535 abs(t1) > "1e12" && (t1 = .5);
1536 abs(t2) > "1e12" && (t2 = .5);
1537 if (t1 > 0 && t1 < 1) {
1538 dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t1);
1542 if (t2 > 0 && t2 < 1) {
1543 dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t2);
1548 min: {x: mmin[apply](0, x), y: mmin[apply](0, y)},
1549 max: {x: mmax[apply](0, x), y: mmax[apply](0, y)}
1552 path2curve = R._path2curve = cacher(function (path, path2) {
1553 var p = pathToAbsolute(path),
1554 p2 = path2 && pathToAbsolute(path2),
1555 attrs = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null},
1556 attrs2 = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null},
1557 processPath = function (path, d) {
1560 return ["C", d.x, d.y, d.x, d.y, d.x, d.y];
1562 !(path[0] in {T:1, Q:1}) && (d.qx = d.qy = null);
1569 path = ["C"][concat](a2c[apply](0, [d.x, d.y][concat](path.slice(1))));
1572 nx = d.x + (d.x - (d.bx || d.x));
1573 ny = d.y + (d.y - (d.by || d.y));
1574 path = ["C", nx, ny][concat](path.slice(1));
1577 d.qx = d.x + (d.x - (d.qx || d.x));
1578 d.qy = d.y + (d.y - (d.qy || d.y));
1579 path = ["C"][concat](q2c(d.x, d.y, d.qx, d.qy, path[1], path[2]));
1584 path = ["C"][concat](q2c(d.x, d.y, path[1], path[2], path[3], path[4]));
1587 path = ["C"][concat](l2c(d.x, d.y, path[1], path[2]));
1590 path = ["C"][concat](l2c(d.x, d.y, path[1], d.y));
1593 path = ["C"][concat](l2c(d.x, d.y, d.x, path[1]));
1596 path = ["C"][concat](l2c(d.x, d.y, d.X, d.Y));
1601 fixArc = function (pp, i) {
1602 if (pp[i].length > 7) {
1606 pp.splice(i++, 0, ["C"][concat](pi.splice(0, 6)));
1609 ii = mmax(p.length, p2 && p2.length || 0);
1612 fixM = function (path1, path2, a1, a2, i) {
1613 if (path1 && path2 && path1[i][0] == "M" && path2[i][0] != "M") {
1614 path2.splice(i, 0, ["M", a2.x, a2.y]);
1619 ii = mmax(p.length, p2 && p2.length || 0);
1622 for (var i = 0, ii = mmax(p.length, p2 && p2.length || 0); i < ii; i++) {
1623 p[i] = processPath(p[i], attrs);
1625 p2 && (p2[i] = processPath(p2[i], attrs2));
1626 p2 && fixArc(p2, i);
1627 fixM(p, p2, attrs, attrs2, i);
1628 fixM(p2, p, attrs2, attrs, i);
1631 seglen = seg.length,
1632 seg2len = p2 && seg2.length;
1633 attrs.x = seg[seglen - 2];
1634 attrs.y = seg[seglen - 1];
1635 attrs.bx = toFloat(seg[seglen - 4]) || attrs.x;
1636 attrs.by = toFloat(seg[seglen - 3]) || attrs.y;
1637 attrs2.bx = p2 && (toFloat(seg2[seg2len - 4]) || attrs2.x);
1638 attrs2.by = p2 && (toFloat(seg2[seg2len - 3]) || attrs2.y);
1639 attrs2.x = p2 && seg2[seg2len - 2];
1640 attrs2.y = p2 && seg2[seg2len - 1];
1642 return p2 ? [p, p2] : p;
1643 }, null, pathClone),
1644 parseDots = R._parseDots = cacher(function (gradient) {
1646 for (var i = 0, ii = gradient.length; i < ii; i++) {
1648 par = gradient[i].match(/^([^:]*):?([\d\.]*)/);
1649 dot.color = R.getRGB(par[1]);
1650 if (dot.color.error) {
1653 dot.color = dot.color.hex;
1654 par[2] && (dot.offset = par[2] + "%");
1657 for (i = 1, ii = dots.length - 1; i < ii; i++) {
1658 if (!dots[i].offset) {
1659 var start = toFloat(dots[i - 1].offset || 0),
1661 for (var j = i + 1; j < ii; j++) {
1662 if (dots[j].offset) {
1663 end = dots[j].offset;
1672 var d = (end - start) / (j - i + 1);
1673 for (; i < j; i++) {
1675 dots[i].offset = start + "%";
1681 tear = R._tear = function (el, paper) {
1682 el == paper.top && (paper.top = el.prev);
1683 el == paper.bottom && (paper.bottom = el.next);
1684 el.next && (el.next.prev = el.prev);
1685 el.prev && (el.prev.next = el.next);
1687 tofront = R._tofront = function (el, paper) {
1688 if (paper.top === el) {
1693 el.prev = paper.top;
1694 paper.top.next = el;
1697 toback = R._toback = function (el, paper) {
1698 if (paper.bottom === el) {
1702 el.next = paper.bottom;
1704 paper.bottom.prev = el;
1707 insertafter = R._insertafter = function (el, el2, paper) {
1709 el2 == paper.top && (paper.top = el);
1710 el2.next && (el2.next.prev = el);
1715 insertbefore = R._insertbefore = function (el, el2, paper) {
1717 el2 == paper.bottom && (paper.bottom = el);
1718 el2.prev && (el2.prev.next = el);
1723 removed = function (methodname) {
1724 return function () {
1725 throw new Error("Rapha\xebl: you are calling to method \u201c" + methodname + "\u201d of removed object");
1728 extractTransform = R._extractTransform = function (el, tstr) {
1730 return el._.transform;
1732 tstr = Str(tstr).replace(/\.{3}|\u2026/g, el._.transform || E);
1733 var tdata = R.parseTransformString(tstr),
1741 _.transform = tdata || [];
1743 for (var i = 0, ii = tdata.length; i < ii; i++) {
1746 command = Str(t[0]).toLowerCase(),
1747 absolute = t[0] != command,
1748 inver = absolute ? m.invert() : 0,
1754 if (command == "t" && tlen == 3) {
1758 x2 = inver.x(t[1], t[2]);
1759 y2 = inver.y(t[1], t[2]);
1760 m.translate(x2 - x1, y2 - y1);
1762 m.translate(t[1], t[2]);
1764 } else if (command == "r") {
1766 bb = bb || el.getBBox(1);
1767 m.rotate(t[1], bb.x + bb.width / 2, bb.y + bb.height / 2);
1769 } else if (tlen == 4) {
1771 x2 = inver.x(t[2], t[3]);
1772 y2 = inver.y(t[2], t[3]);
1773 m.rotate(t[1], x2, y2);
1775 m.rotate(t[1], t[2], t[3]);
1779 } else if (command == "s") {
1780 if (tlen == 2 || tlen == 3) {
1781 bb = bb || el.getBBox(1);
1782 m.scale(t[1], t[tlen - 1], bb.x + bb.width / 2, bb.y + bb.height / 2);
1785 } else if (tlen == 5) {
1787 x2 = inver.x(t[3], t[4]);
1788 y2 = inver.y(t[3], t[4]);
1789 m.scale(t[1], t[2], x2, y2);
1791 m.scale(t[1], t[2], t[3], t[4]);
1796 } else if (command == "m" && tlen == 7) {
1797 m.add(t[1], t[2], t[3], t[4], t[5], t[6]);
1812 if (sx == 1 && sy == 1 && !deg && _.bbox) {
1819 getEmpty = function (item) {
1821 switch (l.toLowerCase()) {
1822 case "t": return [l, 0, 0];
1823 case "m": return [l, 1, 0, 0, 1, 0, 0];
1824 case "r": if (item.length == 4) {
1825 return [l, 0, item[2], item[3]];
1829 case "s": if (item.length == 5) {
1830 return [l, 1, 1, item[3], item[4]];
1831 } else if (item.length == 3) {
1838 equaliseTransform = R._equaliseTransform = function (t1, t2) {
1839 t2 = Str(t2).replace(/\.{3}|\u2026/g, t1);
1840 t1 = R.parseTransformString(t1) || [];
1841 t2 = R.parseTransformString(t2) || [];
1842 var maxlength = mmax(t1.length, t2.length),
1847 for (; i < maxlength; i++) {
1848 tt1 = t1[i] || getEmpty(t2[i]);
1849 tt2 = t2[i] || getEmpty(tt1);
1850 if ((tt1[0] != tt2[0]) ||
1851 (tt1[0].toLowerCase() == "r" && (tt1[2] != tt2[2] || tt1[3] != tt2[3])) ||
1852 (tt1[0].toLowerCase() == "s" && (tt1[3] != tt2[3] || tt1[4] != tt2[4]))
1858 for (j = 0, jj = mmax(tt1.length, tt2.length); j < jj; j++) {
1859 j in tt1 && (from[i][j] = tt1[j]);
1860 j in tt2 && (to[i][j] = tt2[j]);
1868 R._getContainer = function (x, y, w, h) {
1870 container = h == null && !R.is(x, "object") ? g.doc.getElementById(x) : x;
1871 if (container == null) {
1874 if (container.tagName) {
1877 container: container,
1878 width: container.style.pixelWidth || container.offsetWidth,
1879 height: container.style.pixelHeight || container.offsetHeight
1883 container: container,
1898 * Raphael.pathToRelative
1903 * Converts path to relative form
1905 - pathString (string|array) path string or array of segments
1906 = (array) array of segments.
1908 R.pathToRelative = pathToRelative;
1911 * Raphael.path2curve
1916 * Converts path to a new path where all segments are cubic bezier curves.
1918 - pathString (string|array) path string or array of segments
1919 = (array) array of segments.
1921 R.path2curve = path2curve;
1928 * Returns matrix based on given parameters.
1938 R.matrix = function (a, b, c, d, e, f) {
1939 return new Matrix(a, b, c, d, e, f);
1941 function Matrix(a, b, c, d, e, f) {
1958 (function (matrixproto) {
1963 * Adds given matrix to existing one.
1972 - matrix (object) @Matrix
1974 matrixproto.add = function (a, b, c, d, e, f) {
1975 var out = [[], [], []],
1976 m = [[this.a, this.c, this.e], [this.b, this.d, this.f], [0, 0, 1]],
1977 matrix = [[a, c, e], [b, d, f], [0, 0, 1]],
1980 if (a && a instanceof Matrix) {
1981 matrix = [[a.a, a.c, a.e], [a.b, a.d, a.f], [0, 0, 1]];
1984 for (x = 0; x < 3; x++) {
1985 for (y = 0; y < 3; y++) {
1987 for (z = 0; z < 3; z++) {
1988 res += m[x][z] * matrix[z][y];
2004 * Returns inverted version of the matrix
2007 matrixproto.invert = function () {
2009 x = me.a * me.d - me.b * me.c;
2010 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);
2016 * Returns copy of the matrix
2019 matrixproto.clone = function () {
2020 return new Matrix(this.a, this.b, this.c, this.d, this.e, this.f);
2026 * Translate the matrix
2031 matrixproto.translate = function (x, y) {
2032 this.add(1, 0, 0, 1, x, y);
2041 - y (number) #optional
2042 - cx (number) #optional
2043 - cy (number) #optional
2045 matrixproto.scale = function (x, y, cx, cy) {
2046 y == null && (y = x);
2047 (cx || cy) && this.add(1, 0, 0, 1, cx, cy);
2048 this.add(x, 0, 0, y, 0, 0);
2049 (cx || cy) && this.add(1, 0, 0, 1, -cx, -cy);
2055 * Rotates the matrix
2061 matrixproto.rotate = function (a, x, y) {
2065 var cos = +math.cos(a).toFixed(9),
2066 sin = +math.sin(a).toFixed(9);
2067 this.add(cos, sin, -sin, cos, x, y);
2068 this.add(1, 0, 0, 1, -x, -y);
2074 * Return x coordinate for given point after transformation described by the matrix. See also @Matrix.y
2080 matrixproto.x = function (x, y) {
2081 return x * this.a + y * this.c + this.e;
2087 * Return y coordinate for given point after transformation described by the matrix. See also @Matrix.x
2093 matrixproto.y = function (x, y) {
2094 return x * this.b + y * this.d + this.f;
2096 matrixproto.get = function (i) {
2097 return +this[Str.fromCharCode(97 + i)].toFixed(4);
2099 matrixproto.toString = function () {
2101 "matrix(" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)].join() + ")" :
2102 [this.get(0), this.get(2), this.get(1), this.get(3), 0, 0].join();
2104 matrixproto.toFilter = function () {
2105 return "progid:DXImageTransform.Microsoft.Matrix(M11=" + this.get(0) +
2106 ", M12=" + this.get(2) + ", M21=" + this.get(1) + ", M22=" + this.get(3) +
2107 ", Dx=" + this.get(4) + ", Dy=" + this.get(5) + ", sizingmethod='auto expand')";
2109 matrixproto.offset = function () {
2110 return [this.e.toFixed(4), this.f.toFixed(4)];
2113 return a[0] * a[0] + a[1] * a[1];
2115 function normalize(a) {
2116 var mag = math.sqrt(norm(a));
2117 a[0] && (a[0] /= mag);
2118 a[1] && (a[1] /= mag);
2124 * Splits matrix into primitive transformations
2125 = (object) in format:
2126 o dx (number) translation by x
2127 o dy (number) translation by y
2128 o scalex (number) scale by x
2129 o scaley (number) scale by y
2130 o shear (number) shear
2131 o rotate (number) rotation in deg
2132 o isSimple (boolean) could it be represented via simple transformations
2134 matrixproto.split = function () {
2141 var row = [[this.a, this.c], [this.b, this.d]];
2142 out.scalex = math.sqrt(norm(row[0]));
2145 out.shear = row[0][0] * row[1][0] + row[0][1] * row[1][1];
2146 row[1] = [row[1][0] - row[0][0] * out.shear, row[1][1] - row[0][1] * out.shear];
2148 out.scaley = math.sqrt(norm(row[1]));
2150 out.shear /= out.scaley;
2153 var sin = -row[0][1],
2156 out.rotate = R.deg(math.acos(cos));
2158 out.rotate = 360 - out.rotate;
2161 out.rotate = R.deg(math.asin(sin));
2164 out.isSimple = !+out.shear.toFixed(9) && (out.scalex.toFixed(9) == out.scaley.toFixed(9) || !out.rotate);
2165 out.isSuperSimple = !+out.shear.toFixed(9) && out.scalex.toFixed(9) == out.scaley.toFixed(9) && !out.rotate;
2166 out.noRotation = !+out.shear.toFixed(9) && !out.rotate;
2170 * Matrix.toTransformString
2173 * Return transform string that represents given matrix
2174 = (string) transform string
2176 matrixproto.toTransformString = function (shorter) {
2177 var s = shorter || this[split]();
2179 return "t" + [s.dx, s.dy] + "s" + [s.scalex, s.scaley, 0, 0] + "r" + [s.rotate, 0, 0];
2181 return "m" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)];
2184 })(Matrix.prototype);
2186 // WebKit rendering bug workaround method
2187 var version = navigator.userAgent.match(/Version\/(.*?)\s/) || navigator.userAgent.match(/Chrome\/(\d+)/);
2188 if ((navigator.vendor == "Apple Computer, Inc.") && (version && version[1] < 4 || navigator.platform.slice(0, 2) == "iP") ||
2189 (navigator.vendor == "Google Inc." && version && version[1] < 8)) {
2194 * There is an inconvenient rendering bug in Safari (WebKit):
2195 * sometimes the rendering should be forced.
2196 * This method should help with dealing with this bug.
2198 paperproto.safari = function () {
2199 var rect = this.rect(-99, -99, this.width + 99, this.height + 99).attr({stroke: "none"});
2200 setTimeout(function () {rect.remove();});
2203 paperproto.safari = fun;
2206 var preventDefault = function () {
2207 this.returnValue = false;
2209 preventTouch = function () {
2210 return this.originalEvent.preventDefault();
2212 stopPropagation = function () {
2213 this.cancelBubble = true;
2215 stopTouch = function () {
2216 return this.originalEvent.stopPropagation();
2218 addEvent = (function () {
2219 if (g.doc.addEventListener) {
2220 return function (obj, type, fn, element) {
2221 var realName = supportsTouch && touchMap[type] ? touchMap[type] : type,
2223 var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
2224 scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft,
2225 x = e.clientX + scrollX,
2226 y = e.clientY + scrollY;
2227 if (supportsTouch && touchMap[has](type)) {
2228 for (var i = 0, ii = e.targetTouches && e.targetTouches.length; i < ii; i++) {
2229 if (e.targetTouches[i].target == obj) {
2231 e = e.targetTouches[i];
2232 e.originalEvent = olde;
2233 e.preventDefault = preventTouch;
2234 e.stopPropagation = stopTouch;
2239 return fn.call(element, e, x, y);
2241 obj.addEventListener(realName, f, false);
2242 return function () {
2243 obj.removeEventListener(realName, f, false);
2247 } else if (g.doc.attachEvent) {
2248 return function (obj, type, fn, element) {
2249 var f = function (e) {
2250 e = e || g.win.event;
2251 var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
2252 scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft,
2253 x = e.clientX + scrollX,
2254 y = e.clientY + scrollY;
2255 e.preventDefault = e.preventDefault || preventDefault;
2256 e.stopPropagation = e.stopPropagation || stopPropagation;
2257 return fn.call(element, e, x, y);
2259 obj.attachEvent("on" + type, f);
2260 var detacher = function () {
2261 obj.detachEvent("on" + type, f);
2269 dragMove = function (e) {
2272 scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
2273 scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft,
2278 if (supportsTouch) {
2279 var i = e.touches.length,
2282 touch = e.touches[i];
2283 if (touch.identifier == dragi.el._drag.id) {
2286 (e.originalEvent ? e.originalEvent : e).preventDefault();
2293 var node = dragi.el.node,
2295 next = node.nextSibling,
2296 parent = node.parentNode,
2297 display = node.style.display;
2298 g.win.opera && parent.removeChild(node);
2299 node.style.display = "none";
2300 o = dragi.el.paper.getElementByPoint(x, y);
2301 node.style.display = display;
2302 g.win.opera && (next ? parent.insertBefore(node, next) : parent.appendChild(node));
2303 o && eve("drag.over." + dragi.el.id, dragi.el, o);
2306 eve("drag.move." + dragi.el.id, dragi.move_scope || dragi.el, x - dragi.el._drag.x, y - dragi.el._drag.y, x, y, e);
2309 dragUp = function (e) {
2310 R.unmousemove(dragMove).unmouseup(dragUp);
2311 var i = drag.length,
2315 dragi.el._drag = {};
2316 eve("drag.end." + dragi.el.id, dragi.end_scope || dragi.start_scope || dragi.move_scope || dragi.el, e);
2322 [ property (object) ]
2324 * You can add your own method to elements. This is usefull when you want to hack default functionality or
2325 * want to wrap some common transformation or attributes in one method. In difference to canvas methods,
2326 * you can redefine element method at any time. Expending element methods wouldn’t affect set.
2328 | Raphael.el.red = function () {
2329 | this.attr({fill: "#f00"});
2332 | paper.circle(100, 100, 20).red();
2334 elproto = R.el = {};
2339 * Adds event handler for click for the element.
2341 - handler (function) handler for the event
2348 * Removes event handler for click for the element.
2350 - handler (function) handler for the event
2358 * Adds event handler for double click for the element.
2360 - handler (function) handler for the event
2364 * Element.undblclick
2367 * Removes event handler for double click for the element.
2369 - handler (function) handler for the event
2377 * Adds event handler for mousedown for the element.
2379 - handler (function) handler for the event
2383 * Element.unmousedown
2386 * Removes event handler for mousedown for the element.
2388 - handler (function) handler for the event
2396 * Adds event handler for mousemove for the element.
2398 - handler (function) handler for the event
2402 * Element.unmousemove
2405 * Removes event handler for mousemove for the element.
2407 - handler (function) handler for the event
2415 * Adds event handler for mouseout for the element.
2417 - handler (function) handler for the event
2421 * Element.unmouseout
2424 * Removes event handler for mouseout for the element.
2426 - handler (function) handler for the event
2434 * Adds event handler for mouseover for the element.
2436 - handler (function) handler for the event
2440 * Element.unmouseover
2443 * Removes event handler for mouseover for the element.
2445 - handler (function) handler for the event
2453 * Adds event handler for mouseup for the element.
2455 - handler (function) handler for the event
2462 * Removes event handler for mouseup for the element.
2464 - handler (function) handler for the event
2469 * Element.touchstart
2472 * Adds event handler for touchstart for the element.
2474 - handler (function) handler for the event
2478 * Element.untouchstart
2481 * Removes event handler for touchstart for the element.
2483 - handler (function) handler for the event
2491 * Adds event handler for touchmove for the element.
2493 - handler (function) handler for the event
2497 * Element.untouchmove
2500 * Removes event handler for touchmove for the element.
2502 - handler (function) handler for the event
2510 * Adds event handler for touchend for the element.
2512 - handler (function) handler for the event
2516 * Element.untouchend
2519 * Removes event handler for touchend for the element.
2521 - handler (function) handler for the event
2526 * Element.touchcancel
2529 * Adds event handler for touchcancel for the element.
2531 - handler (function) handler for the event
2535 * Element.untouchcancel
2538 * Removes event handler for touchcancel for the element.
2540 - handler (function) handler for the event
2543 for (var i = events.length; i--;) {
2544 (function (eventName) {
2545 R[eventName] = elproto[eventName] = function (fn, scope) {
2546 if (R.is(fn, "function")) {
2547 this.events = this.events || [];
2548 this.events.push({name: eventName, f: fn, unbind: addEvent(this.shape || this.node || g.doc, eventName, fn, scope || this)});
2552 R["un" + eventName] = elproto["un" + eventName] = function (fn) {
2553 var events = this.events,
2555 while (l--) if (events[l].name == eventName && events[l].f == fn) {
2557 events.splice(l, 1);
2558 !events.length && delete this.events;
2570 * Adds or retrieves given value asociated with given key.
2572 * See also @Element.removeData
2574 - key (string) key to store data
2575 - value (any) #optional value to store
2577 * or, if value is not specified:
2580 | for (var i = 0, i < 5, i++) {
2581 | paper.circle(10 + 15 * i, 10, 10)
2582 | .attr({fill: "#000"})
2584 | .click(function () {
2585 | alert(this.data("i"));
2589 elproto.data = function (key, value) {
2590 var data = eldata[this.id] = eldata[this.id] || {};
2591 if (arguments.length == 1) {
2592 if (R.is(key, "object")) {
2593 for (var i in key) if (key[has](i)) {
2594 this.data(i, key[i]);
2598 eve("data.get." + this.id, this, data[key], key);
2602 eve("data.set." + this.id, this, value, key);
2606 * Element.removeData
2609 * Removes value associated with an element by given key.
2610 * If key is not provided, removes all the data of the element.
2612 - key (string) #optional key
2615 elproto.removeData = function (key) {
2617 eldata[this.id] = {};
2619 eldata[this.id] && delete eldata[this.id][key];
2627 * Adds event handlers for hover for the element.
2629 - f_in (function) handler for hover in
2630 - f_out (function) handler for hover out
2631 - icontext (object) #optional context for hover in handler
2632 - ocontext (object) #optional context for hover out handler
2635 elproto.hover = function (f_in, f_out, scope_in, scope_out) {
2636 return this.mouseover(f_in, scope_in).mouseout(f_out, scope_out || scope_in);
2642 * Removes event handlers for hover for the element.
2644 - f_in (function) handler for hover in
2645 - f_out (function) handler for hover out
2648 elproto.unhover = function (f_in, f_out) {
2649 return this.unmouseover(f_in).unmouseout(f_out);
2655 * Adds event handlers for drag of the element.
2657 - onmove (function) handler for moving
2658 - onstart (function) handler for drag start
2659 - onend (function) handler for drag end
2660 - mcontext (object) #optional context for moving handler
2661 - scontext (object) #optional context for drag start handler
2662 - econtext (object) #optional context for drag end handler
2663 * Additionaly following `drag` events will be triggered: `drag.start.<id>` on start,
2664 * `drag.end.<id>` on end and `drag.move.<id>` on every move. When element will be dragged over another element
2665 * `drag.over.<id>` will be fired as well.
2667 * Start event and start handler will be called in specified context or in context of the element with following parameters:
2668 o x (number) x position of the mouse
2669 o y (number) y position of the mouse
2670 o event (object) DOM event object
2671 * Move event and move handler will be called in specified context or in context of the element with following parameters:
2672 o dx (number) shift by x from the start point
2673 o dy (number) shift by y from the start point
2674 o x (number) x position of the mouse
2675 o y (number) y position of the mouse
2676 o event (object) DOM event object
2677 * End event and end handler will be called in specified context or in context of the element with following parameters:
2678 o event (object) DOM event object
2681 elproto.drag = function (onmove, onstart, onend, move_scope, start_scope, end_scope) {
2683 (e.originalEvent || e).preventDefault();
2684 var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
2685 scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft;
2686 this._drag.x = e.clientX + scrollX;
2687 this._drag.y = e.clientY + scrollY;
2688 this._drag.id = e.identifier;
2689 !drag.length && R.mousemove(dragMove).mouseup(dragUp);
2690 drag.push({el: this, move_scope: move_scope, start_scope: start_scope, end_scope: end_scope});
2691 onstart && eve.on("drag.start." + this.id, onstart);
2692 onmove && eve.on("drag.move." + this.id, onmove);
2693 onend && eve.on("drag.end." + this.id, onend);
2694 eve("drag.start." + this.id, start_scope || move_scope || this, e.clientX + scrollX, e.clientY + scrollY, e);
2697 this.mousedown(start);
2701 * Element.onDragOver
2704 * Shortcut for assigning event handler for `drag.over.<id>` event, where id is id of the element (see @Element.id).
2706 - f (function) handler for event, first argument would be the element you are dragging over
2708 elproto.onDragOver = function (f) {
2709 f ? eve.on("drag.over." + this.id, f) : eve.unbind("drag.over." + this.id);
2715 * Removes all drag event handlers from given element.
2717 elproto.undrag = function () {
2718 var i = drag.length;
2719 while (i--) if (drag[i].el == this) {
2720 R.unmousedown(drag[i].start);
2721 drag.splice(i++, 1);
2722 eve.unbind("drag.*." + this.id);
2724 !drag.length && R.unmousemove(dragMove).unmouseup(dragUp);
2734 - x (number) x coordinate of the centre
2735 - y (number) y coordinate of the centre
2737 = (object) Raphaël element object with type “circle”
2740 | var c = paper.circle(50, 50, 40);
2742 paperproto.circle = function (x, y, r) {
2743 var out = R._engine.circle(this, x || 0, y || 0, r || 0);
2744 this.__set__ && this.__set__.push(out);
2751 * Draws a rectangle.
2755 - x (number) x coordinate of the top left corner
2756 - y (number) y coordinate of the top left corner
2757 - width (number) width
2758 - height (number) height
2759 - r (number) #optional radius for rounded corners, default is 0
2760 = (object) Raphaël element object with type “rect”
2763 | // regular rectangle
2764 | var c = paper.rect(10, 10, 50, 50);
2765 | // rectangle with rounded corners
2766 | var c = paper.rect(40, 40, 50, 50, 10);
2768 paperproto.rect = function (x, y, w, h, r) {
2769 var out = R._engine.rect(this, x || 0, y || 0, w || 0, h || 0, r || 0);
2770 this.__set__ && this.__set__.push(out);
2781 - x (number) x coordinate of the centre
2782 - y (number) y coordinate of the centre
2783 - rx (number) horizontal radius
2784 - ry (number) vertical radius
2785 = (object) Raphaël element object with type “ellipse”
2788 | var c = paper.ellipse(50, 50, 40, 20);
2790 paperproto.ellipse = function (x, y, rx, ry) {
2791 var out = R._engine.ellipse(this, x || 0, y || 0, rx || 0, ry || 0);
2792 this.__set__ && this.__set__.push(out);
2799 * Creates a path element by given path data string.
2801 - pathString (string) #optional path string in SVG format.
2802 * Path string consists of one-letter commands, followed by comma seprarated arguments in numercal form. Example:
2804 * 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.
2806 # <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>
2807 # <table><thead><tr><th>Command</th><th>Name</th><th>Parameters</th></tr></thead><tbody>
2808 # <tr><td>M</td><td>moveto</td><td>(x y)+</td></tr>
2809 # <tr><td>Z</td><td>closepath</td><td>(none)</td></tr>
2810 # <tr><td>L</td><td>lineto</td><td>(x y)+</td></tr>
2811 # <tr><td>H</td><td>horizontal lineto</td><td>x+</td></tr>
2812 # <tr><td>V</td><td>vertical lineto</td><td>y+</td></tr>
2813 # <tr><td>C</td><td>curveto</td><td>(x1 y1 x2 y2 x y)+</td></tr>
2814 # <tr><td>S</td><td>smooth curveto</td><td>(x2 y2 x y)+</td></tr>
2815 # <tr><td>Q</td><td>quadratic Bézier curveto</td><td>(x1 y1 x y)+</td></tr>
2816 # <tr><td>T</td><td>smooth quadratic Bézier curveto</td><td>(x y)+</td></tr>
2817 # <tr><td>A</td><td>elliptical arc</td><td>(rx ry x-axis-rotation large-arc-flag sweep-flag x y)+</td></tr>
2818 # <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>
2819 * * “Catmull-Rom curveto” is a not standard SVG command and added in 2.0 to make life easier.
2821 | var c = paper.path("M10 10L90 90");
2822 | // draw a diagonal line:
2823 | // move to 10,10, line to 90,90
2825 paperproto.path = function (pathString) {
2826 pathString && !R.is(pathString, string) && !R.is(pathString[0], array) && (pathString += E);
2827 var out = R._engine.path(R.format[apply](R, arguments), this);
2828 this.__set__ && this.__set__.push(out);
2835 * Embeds an image into the surface.
2839 - src (string) URI of the source image
2840 - x (number) x coordinate position
2841 - y (number) y coordinate position
2842 - width (number) width of the image
2843 - height (number) height of the image
2844 = (object) Raphaël element object with type “image”
2847 | var c = paper.image("apple.png", 10, 10, 80, 80);
2849 paperproto.image = function (src, x, y, w, h) {
2850 var out = R._engine.image(this, src || "about:blank", x || 0, y || 0, w || 0, h || 0);
2851 this.__set__ && this.__set__.push(out);
2858 * Draws a text string. If you need line breaks, put “\n” in the string.
2862 - x (number) x coordinate position
2863 - y (number) y coordinate position
2864 - text (string) The text string to draw
2865 = (object) Raphaël element object with type “text”
2868 | var t = paper.text(50, 50, "Raphaël\nkicks\nbutt!");
2870 paperproto.text = function (x, y, text) {
2871 var out = R._engine.text(this, x || 0, y || 0, Str(text));
2872 this.__set__ && this.__set__.push(out);
2879 * Creates array-like object to keep and operate several elements at once.
2880 * Warning: it doesn’t create any elements for itself in the page, it just groups existing elements.
2881 * Sets act as pseudo elements — all methods available to an element can be used on a set.
2882 = (object) array-like object that represents set of elements
2885 | var st = paper.set();
2887 | paper.circle(10, 10, 5),
2888 | paper.circle(30, 10, 5)
2890 | st.attr({fill: "red"}); // changes the fill of both circles
2892 paperproto.set = function (itemsArray) {
2893 !R.is(itemsArray, "array") && (itemsArray = Array.prototype.splice.call(arguments, 0, arguments.length));
2894 var out = new Set(itemsArray);
2895 this.__set__ && this.__set__.push(out);
2902 * Creates @Paper.set. All elements that will be created after calling this method and before calling
2903 * @Paper.setFinish will be added to the set.
2907 | paper.circle(10, 10, 5),
2908 | paper.circle(30, 10, 5)
2909 | var st = paper.setFinish();
2910 | st.attr({fill: "red"}); // changes the fill of both circles
2912 paperproto.setStart = function (set) {
2913 this.__set__ = set || this.set();
2919 * See @Paper.setStart. This method finishes catching and returns resulting set.
2923 paperproto.setFinish = function (set) {
2924 var out = this.__set__;
2925 delete this.__set__;
2932 * If you need to change dimensions of the canvas call this method
2936 - width (number) new width of the canvas
2937 - height (number) new height of the canvas
2939 | var st = paper.set();
2941 | paper.circle(10, 10, 5),
2942 | paper.circle(30, 10, 5)
2944 | st.attr({fill: "red"});
2946 paperproto.setSize = function (width, height) {
2947 return R._engine.setSize.call(this, width, height);
2953 * Sets the view box of the paper. Practically it gives you ability to zoom and pan whole paper surface by
2954 * specifying new boundaries.
2958 - x (number) new x position, default is `0`
2959 - y (number) new y position, default is `0`
2960 - w (number) new width of the canvas
2961 - h (number) new height of the canvas
2962 - fit (boolean) `true` if you want graphics to fit into new boundary box
2964 paperproto.setViewBox = function (x, y, w, h, fit) {
2965 return R._engine.setViewBox.call(this, x, y, w, h, fit);
2971 * Points to the topmost element on the paper
2977 * Points to the bottom element on the paper
2979 paperproto.top = paperproto.bottom = null;
2984 * Points to the @Raphael object/function
2986 paperproto.raphael = R;
2987 var getOffset = function (elem) {
2988 var box = elem.getBoundingClientRect(),
2989 doc = elem.ownerDocument,
2991 docElem = doc.documentElement,
2992 clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0,
2993 top = box.top + (g.win.pageYOffset || docElem.scrollTop || body.scrollTop ) - clientTop,
2994 left = box.left + (g.win.pageXOffset || docElem.scrollLeft || body.scrollLeft) - clientLeft;
3001 * Paper.getElementByPoint
3004 * Returns you topmost element under given point.
3006 = (object) Raphaël element object
3009 - x (number) x coordinate from the top left corner of the window
3010 - y (number) y coordinate from the top left corner of the window
3012 | paper.getElementByPoint(mouseX, mouseY).attr({stroke: "#f00"});
3014 paperproto.getElementByPoint = function (x, y) {
3017 target = g.doc.elementFromPoint(x, y);
3018 if (g.win.opera && target.tagName == "svg") {
3019 var so = getOffset(svg),
3020 sr = svg.createSVGRect();
3023 sr.width = sr.height = 1;
3024 var hits = svg.getIntersectionList(sr, null);
3026 target = hits[hits.length - 1];
3032 while (target.parentNode && target != svg.parentNode && !target.raphael) {
3033 target = target.parentNode;
3035 target == paper.canvas.parentNode && (target = svg);
3036 target = target && target.raphael ? paper.getById(target.raphaelid) : null;
3043 * Returns you element by its internal ID.
3048 = (object) Raphaël element object
3050 paperproto.getById = function (id) {
3051 var bot = this.bottom;
3064 * Executes given function for each element on the paper
3066 * If callback function returns `false` it will stop loop running.
3070 - callback (function) function to run
3071 - thisArg (object) context object for the callback
3072 = (object) Paper object
3074 paperproto.forEach = function (callback, thisArg) {
3075 var bot = this.bottom;
3077 if (callback.call(thisArg, bot) === false) {
3085 return this.x + S + this.y;
3087 function x_y_w_h() {
3088 return this.x + S + this.y + S + this.width + " \xd7 " + this.height;
3094 * Return bounding box for a given element
3098 - isWithoutTransform (boolean) flag, `true` if you want to have bounding box before transformations. Default is `false`.
3099 = (object) Bounding box object:
3101 o x: (number) top left corner x
3102 o y: (number) top left corner y
3103 o width: (number) width
3104 o height: (number) height
3107 elproto.getBBox = function (isWithoutTransform) {
3112 if (isWithoutTransform) {
3113 if (_.dirty || !_.bboxwt) {
3114 this.realPath = getPath[this.type](this);
3115 _.bboxwt = pathDimensions(this.realPath);
3116 _.bboxwt.toString = x_y_w_h;
3121 if (_.dirty || _.dirtyT || !_.bbox) {
3122 if (_.dirty || !this.realPath) {
3124 this.realPath = getPath[this.type](this);
3126 _.bbox = pathDimensions(mapPath(this.realPath, this.matrix));
3127 _.bbox.toString = x_y_w_h;
3128 _.dirty = _.dirtyT = 0;
3136 = (object) clone of a given element
3139 elproto.clone = function () {
3143 var out = this.paper[this.type]().attr(this.attr());
3144 this.__set__ && this.__set__.push(out);
3151 * Return set of elements that create glow-like effect around given element. See @Paper.set.
3153 * Note: Glow is not connected to the element. If you change element attributes it won’t adjust itself.
3157 - glow (object) #optional parameters object with all properties optional:
3159 o width (number) size of the glow, default is `10`
3160 o fill (boolean) will it be filled, default is `false`
3161 o opacity (number) opacity, default is `0.5`
3162 o offsetx (number) horizontal offset, default is `0`
3163 o offsety (number) vertical offset, default is `0`
3164 o color (string) glow colour, default is `black`
3166 = (object) @Paper.set of elements that represents glow
3168 elproto.glow = function (glow) {
3169 if (this.type == "text") {
3174 width: (glow.width || 10) + (+this.attr("stroke-width") || 1),
3175 fill: glow.fill || false,
3176 opacity: glow.opacity || .5,
3177 offsetx: glow.offsetx || 0,
3178 offsety: glow.offsety || 0,
3179 color: glow.color || "#000"
3184 path = this.realPath || getPath[this.type](this);
3185 path = this.matrix ? mapPath(path, this.matrix) : path;
3186 for (var i = 1; i < c + 1; i++) {
3187 out.push(r.path(path).attr({
3189 fill: s.fill ? s.color : "none",
3190 "stroke-linejoin": "round",
3191 "stroke-linecap": "round",
3192 "stroke-width": +(s.width / c * i).toFixed(3),
3193 opacity: +(s.opacity / c).toFixed(3)
3196 return out.insertBefore(this).translate(s.offsetx, s.offsety);
3198 var curveslengths = {},
3199 getPointAtSegmentLength = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length) {
3202 name = [p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y].join(),
3203 cache = curveslengths[name],
3205 !cache && (curveslengths[name] = cache = {data: []});
3206 cache.timer && clearTimeout(cache.timer);
3207 cache.timer = setTimeout(function () {delete curveslengths[name];}, 2e3);
3208 if (length != null && !cache.precision) {
3209 var total = getPointAtSegmentLength(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y);
3210 cache.precision = ~~total * 10;
3213 precision = cache.precision || precision;
3214 for (var i = 0; i < precision + 1; i++) {
3215 if (cache.data[i * precision]) {
3216 dot = cache.data[i * precision];
3218 dot = R.findDotsAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, i / precision);
3219 cache.data[i * precision] = dot;
3221 i && (len += pow(pow(old.x - dot.x, 2) + pow(old.y - dot.y, 2), .5));
3222 if (length != null && len >= length) {
3227 if (length == null) {
3231 getLengthFactory = function (istotal, subpath) {
3232 return function (path, length, onlystart) {
3233 path = path2curve(path);
3234 var x, y, p, l, sp = "", subpaths = {}, point,
3236 for (var i = 0, ii = path.length; i < ii; i++) {
3242 l = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6]);
3243 if (len + l > length) {
3244 if (subpath && !subpaths.start) {
3245 point = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6], length - len);
3246 sp += ["C" + point.start.x, point.start.y, point.m.x, point.m.y, point.x, point.y];
3247 if (onlystart) {return sp;}
3248 subpaths.start = sp;
3249 sp = ["M" + point.x, point.y + "C" + point.n.x, point.n.y, point.end.x, point.end.y, p[5], p[6]].join();
3255 if (!istotal && !subpath) {
3256 point = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6], length - len);
3257 return {x: point.x, y: point.y, alpha: point.alpha};
3264 sp += p.shift() + p;
3267 point = istotal ? len : subpath ? subpaths : R.findDotsAtSegment(x, y, p[0], p[1], p[2], p[3], p[4], p[5], 1);
3268 point.alpha && (point = {x: point.x, y: point.y, alpha: point.alpha});
3272 var getTotalLength = getLengthFactory(1),
3273 getPointAtLength = getLengthFactory(),
3274 getSubpathsAtLength = getLengthFactory(0, 1);
3276 * Raphael.getTotalLength
3279 * Returns length of the given path in pixels.
3283 - path (string) SVG path string.
3287 R.getTotalLength = getTotalLength;
3289 * Raphael.getPointAtLength
3292 * Return coordinates of the point located at the given length on the given path.
3296 - path (string) SVG path string
3299 = (object) representation of the point:
3301 o x: (number) x coordinate
3302 o y: (number) y coordinate
3303 o alpha: (number) angle of derivative
3306 R.getPointAtLength = getPointAtLength;
3308 * Raphael.getSubpath
3311 * Return subpath of a given path from given length to given length.
3315 - path (string) SVG path string
3316 - from (number) position of the start of the segment
3317 - to (number) position of the end of the segment
3319 = (string) pathstring for the segment
3321 R.getSubpath = function (path, from, to) {
3322 if (this.getTotalLength(path) - to < 1e-6) {
3323 return getSubpathsAtLength(path, from).end;
3325 var a = getSubpathsAtLength(path, to, 1);
3326 return from ? getSubpathsAtLength(a, from).end : a;
3329 * Element.getTotalLength
3332 * Returns length of the path in pixels. Only works for element of “path” type.
3335 elproto.getTotalLength = function () {
3336 if (this.type != "path") {return;}
3337 if (this.node.getTotalLength) {
3338 return this.node.getTotalLength();
3340 return getTotalLength(this.attrs.path);
3343 * Element.getPointAtLength
3346 * Return coordinates of the point located at the given length on the given path. Only works for element of “path” type.
3352 = (object) representation of the point:
3354 o x: (number) x coordinate
3355 o y: (number) y coordinate
3356 o alpha: (number) angle of derivative
3359 elproto.getPointAtLength = function (length) {
3360 if (this.type != "path") {return;}
3361 return getPointAtLength(this.attrs.path, length);
3364 * Element.getSubpath
3367 * Return subpath of a given element from given length to given length. Only works for element of “path” type.
3371 - from (number) position of the start of the segment
3372 - to (number) position of the end of the segment
3374 = (string) pathstring for the segment
3376 elproto.getSubpath = function (from, to) {
3377 if (this.type != "path") {return;}
3378 return R.getSubpath(this.attrs.path, from, to);
3381 * Raphael.easing_formulas
3384 * Object that contains easing formulas for animation. You could extend it with your own. By default it has following list of easing:
3387 # <li>“<” or “easeIn” or “ease-in”</li>
3388 # <li>“>” or “easeOut” or “ease-out”</li>
3389 # <li>“<>” or “easeInOut” or “ease-in-out”</li>
3390 # <li>“backIn” or “back-in”</li>
3391 # <li>“backOut” or “back-out”</li>
3392 # <li>“elastic”</li>
3395 # <p>See also <a href="http://raphaeljs.com/easing.html">Easing demo</a>.</p>
3397 var ef = R.easing_formulas = {
3398 linear: function (n) {
3407 "<>": function (n) {
3408 var q = .48 - n / 1.04,
3409 Q = math.sqrt(.1734 + q * q),
3411 X = pow(abs(x), 1 / 3) * (x < 0 ? -1 : 1),
3413 Y = pow(abs(y), 1 / 3) * (y < 0 ? -1 : 1),
3415 return (1 - t) * 3 * t * t + t * t * t;
3417 backIn: function (n) {
3419 return n * n * ((s + 1) * n - s);
3421 backOut: function (n) {
3424 return n * n * ((s + 1) * n + s) + 1;
3426 elastic: function (n) {
3430 return pow(2, -10 * n) * math.sin((n - .075) * (2 * PI) / .3) + 1;
3432 bounce: function (n) {
3441 l = s * n * n + .75;
3443 if (n < (2.5 / p)) {
3445 l = s * n * n + .9375;
3448 l = s * n * n + .984375;
3455 ef.easeIn = ef["ease-in"] = ef["<"];
3456 ef.easeOut = ef["ease-out"] = ef[">"];
3457 ef.easeInOut = ef["ease-in-out"] = ef["<>"];
3458 ef["back-in"] = ef.backIn;
3459 ef["back-out"] = ef.backOut;
3461 var animationElements = [],
3462 requestAnimFrame = window.requestAnimationFrame ||
3463 window.webkitRequestAnimationFrame ||
3464 window.mozRequestAnimationFrame ||
3465 window.oRequestAnimationFrame ||
3466 window.msRequestAnimationFrame ||
3467 function (callback) {
3468 setTimeout(callback, 16);
3470 animation = function () {
3471 var Now = +new Date,
3473 for (; l < animationElements.length; l++) {
3474 var e = animationElements[l];
3475 if (e.el.removed || e.paused) {
3478 var time = Now - e.start,
3491 time = (e.initstatus * e.anim.top - e.prev) / (e.percent - e.prev) * ms;
3492 e.status = e.initstatus;
3493 delete e.initstatus;
3494 e.stop && animationElements.splice(l--, 1);
3496 e.status = (e.prev + (e.percent - e.prev) * (time / ms)) / e.anim.top;
3502 var pos = easing(time / ms);
3503 for (var attr in from) if (from[has](attr)) {
3504 switch (availableAnimAttrs[attr]) {
3506 now = +from[attr] + pos * ms * diff[attr];
3510 upto255(round(from[attr].r + pos * ms * diff[attr].r)),
3511 upto255(round(from[attr].g + pos * ms * diff[attr].g)),
3512 upto255(round(from[attr].b + pos * ms * diff[attr].b))
3517 for (var i = 0, ii = from[attr].length; i < ii; i++) {
3518 now[i] = [from[attr][i][0]];
3519 for (var j = 1, jj = from[attr][i].length; j < jj; j++) {
3520 now[i][j] = +from[attr][i][j] + pos * ms * diff[attr][i][j];
3522 now[i] = now[i].join(S);
3527 if (diff[attr].real) {
3529 for (i = 0, ii = from[attr].length; i < ii; i++) {
3530 now[i] = [from[attr][i][0]];
3531 for (j = 1, jj = from[attr][i].length; j < jj; j++) {
3532 now[i][j] = from[attr][i][j] + pos * ms * diff[attr][i][j];
3536 var get = function (i) {
3537 return +from[attr][i] + pos * ms * diff[attr][i];
3539 // now = [["r", get(2), 0, 0], ["t", get(3), get(4)], ["s", get(0), get(1), 0, 0]];
3540 now = [["m", get(0), get(1), get(2), get(3), get(4), get(5)]];
3544 if (attr == "clip-rect") {
3548 now[i] = +from[attr][i] + pos * ms * diff[attr][i];
3553 var from2 = [][concat](from[attr]);
3555 i = that.paper.customAttributes[attr].length;
3557 now[i] = +from2[i] + pos * ms * diff[attr][i];
3564 (function (id, that, anim) {
3565 setTimeout(function () {
3566 eve("anim.frame." + id, that, anim);
3568 })(that.id, that, e.anim);
3570 (function(f, el, a) {
3571 setTimeout(function() {
3572 eve("anim.frame." + el.id, el, a);
3573 eve("anim.finish." + el.id, el, a);
3574 R.is(f, "function") && f.call(el);
3576 })(e.callback, that, e.anim);
3578 animationElements.splice(l--, 1);
3579 if (e.repeat > 1 && !e.next) {
3580 for (key in to) if (to[has](key)) {
3581 init[key] = e.totalOrigin[key];
3584 runAnimation(e.anim, e.el, e.anim.percents[0], null, e.totalOrigin, e.repeat - 1);
3586 if (e.next && !e.stop) {
3587 runAnimation(e.anim, e.el, e.next, null, e.totalOrigin, e.repeat);
3591 R.svg && that && that.paper && that.paper.safari();
3592 animationElements.length && requestAnimFrame(animation);
3594 upto255 = function (color) {
3595 return color > 255 ? 255 : color < 0 ? 0 : color;
3598 * Element.animateWith
3601 * Acts similar to @Element.animate, but ensure that given animation runs in sync with another given element.
3605 - element (object) element to sync with
3606 - anim (object) animation to sync with
3607 - params (object) #optional final attributes for the element, see also @Element.attr
3608 - ms (number) #optional number of milliseconds for animation to run
3609 - easing (string) #optional easing type. Accept on of @Raphael.easing_formulas or CSS format: `cubic‐bezier(XX, XX, XX, XX)`
3610 - callback (function) #optional callback function. Will be called at the end of animation.
3612 - element (object) element to sync with
3613 - anim (object) animation to sync with
3614 - animation (object) #optional animation object, see @Raphael.animation
3616 = (object) original element
3618 elproto.animateWith = function (element, anim, params, ms, easing, callback) {
3619 var a = params ? R.animation(params, ms, easing, callback) : anim;
3620 status = element.status(anim);
3621 return this.animate(a).status(a, status * anim.ms / a.ms);
3623 function CubicBezierAtTime(t, p1x, p1y, p2x, p2y, duration) {
3625 bx = 3 * (p2x - p1x) - cx,
3628 by = 3 * (p2y - p1y) - cy,
3630 function sampleCurveX(t) {
3631 return ((ax * t + bx) * t + cx) * t;
3633 function solve(x, epsilon) {
3634 var t = solveCurveX(x, epsilon);
3635 return ((ay * t + by) * t + cy) * t;
3637 function solveCurveX(x, epsilon) {
3638 var t0, t1, t2, x2, d2, i;
3639 for(t2 = x, i = 0; i < 8; i++) {
3640 x2 = sampleCurveX(t2) - x;
3641 if (abs(x2) < epsilon) {
3644 d2 = (3 * ax * t2 + 2 * bx) * t2 + cx;
3645 if (abs(d2) < 1e-6) {
3660 x2 = sampleCurveX(t2);
3661 if (abs(x2 - x) < epsilon) {
3669 t2 = (t1 - t0) / 2 + t0;
3673 return solve(t, 1 / (200 * duration));
3675 elproto.onAnimation = function (f) {
3676 f ? eve.on("anim.frame." + this.id, f) : eve.unbind("anim.frame." + this.id);
3679 function Animation(anim, ms) {
3685 for (var attr in anim) if (anim[has](attr)) {
3686 newAnim[toFloat(attr)] = anim[attr];
3687 percents.push(toFloat(attr));
3689 percents.sort(sortByNumber);
3691 this.anim = newAnim;
3692 this.top = percents[percents.length - 1];
3693 this.percents = percents;
3699 * Creates a copy of existing animation object with given delay.
3703 - delay (number) number of ms to pass between animation start and actual animation
3705 = (object) new altered Animation object
3706 | var anim = Raphael.animation({cx: 10, cy: 20}, 2e3);
3707 | circle1.animate(anim); // run the given animation immediately
3708 | circle2.animate(anim.delay(500)); // run the given animation after 500 ms
3710 Animation.prototype.delay = function (delay) {
3711 var a = new Animation(this.anim, this.ms);
3712 a.times = this.times;
3713 a.del = +delay || 0;
3720 * Creates a copy of existing animation object with given repetition.
3724 - repeat (number) number iterations of animation. For infinite animation pass `Infinity`
3726 = (object) new altered Animation object
3728 Animation.prototype.repeat = function (times) {
3729 var a = new Animation(this.anim, this.ms);
3731 a.times = math.floor(mmax(times, 0)) || 1;
3734 function runAnimation(anim, element, percent, status, totalOrigin, times) {
3735 percent = toFloat(percent);
3748 for (i = 0, ii = animationElements.length; i < ii; i++) {
3749 var e = animationElements[i];
3750 if (e.el.id == element.id && e.anim == anim) {
3751 if (e.percent != percent) {
3752 animationElements.splice(i, 1);
3757 element.attr(e.totalOrigin);
3762 status = +to; // NaN
3764 for (var i = 0, ii = anim.percents.length; i < ii; i++) {
3765 if (anim.percents[i] == percent || anim.percents[i] > status * anim.top) {
3766 percent = anim.percents[i];
3767 prev = anim.percents[i - 1] || 0;
3768 ms = ms / anim.top * (percent - prev);
3769 next = anim.percents[i + 1];
3770 params = anim.anim[percent];
3772 } else if (status) {
3773 element.attr(anim.anim[anim.percents[i]]);
3780 for (attr in params) if (params[has](attr)) {
3781 if (availableAnimAttrs[has](attr) || element.paper.customAttributes[has](attr)) {
3782 from[attr] = element.attr(attr);
3783 (from[attr] == null) && (from[attr] = availableAttrs[attr]);
3784 to[attr] = params[attr];
3785 switch (availableAnimAttrs[attr]) {
3787 diff[attr] = (to[attr] - from[attr]) / ms;
3790 from[attr] = R.getRGB(from[attr]);
3791 var toColour = R.getRGB(to[attr]);
3793 r: (toColour.r - from[attr].r) / ms,
3794 g: (toColour.g - from[attr].g) / ms,
3795 b: (toColour.b - from[attr].b) / ms
3799 var pathes = path2curve(from[attr], to[attr]),
3801 from[attr] = pathes[0];
3803 for (i = 0, ii = from[attr].length; i < ii; i++) {
3804 diff[attr][i] = [0];
3805 for (var j = 1, jj = from[attr][i].length; j < jj; j++) {
3806 diff[attr][i][j] = (toPath[i][j] - from[attr][i][j]) / ms;
3812 eq = equaliseTransform(_[attr], to[attr]);
3814 from[attr] = eq.from;
3817 diff[attr].real = true;
3818 for (i = 0, ii = from[attr].length; i < ii; i++) {
3819 diff[attr][i] = [from[attr][i][0]];
3820 for (j = 1, jj = from[attr][i].length; j < jj; j++) {
3821 diff[attr][i][j] = (to[attr][i][j] - from[attr][i][j]) / ms;
3825 var m = (element.matrix || new Matrix),
3827 _: {transform: _.transform},
3828 getBBox: function () {
3829 return element.getBBox(1);
3840 extractTransform(to2, to[attr]);
3841 to[attr] = to2._.transform;
3843 (to2.matrix.a - m.a) / ms,
3844 (to2.matrix.b - m.b) / ms,
3845 (to2.matrix.c - m.c) / ms,
3846 (to2.matrix.d - m.d) / ms,
3847 (to2.matrix.e - m.e) / ms,
3848 (to2.matrix.e - m.f) / ms
3850 // from[attr] = [_.sx, _.sy, _.deg, _.dx, _.dy];
3851 // var to2 = {_:{}, getBBox: function () { return element.getBBox(); }};
3852 // extractTransform(to2, to[attr]);
3854 // (to2._.sx - _.sx) / ms,
3855 // (to2._.sy - _.sy) / ms,
3856 // (to2._.deg - _.deg) / ms,
3857 // (to2._.dx - _.dx) / ms,
3858 // (to2._.dy - _.dy) / ms
3863 var values = Str(params[attr])[split](separator),
3864 from2 = Str(from[attr])[split](separator);
3865 if (attr == "clip-rect") {
3870 diff[attr][i] = (values[i] - from[attr][i]) / ms;
3876 values = [][concat](params[attr]);
3877 from2 = [][concat](from[attr]);
3879 i = element.paper.customAttributes[attr].length;
3881 diff[attr][i] = ((values[i] || 0) - (from2[i] || 0)) / ms;
3887 var easing = params.easing,
3888 easyeasy = R.easing_formulas[easing];
3890 easyeasy = Str(easing).match(bezierrg);
3891 if (easyeasy && easyeasy.length == 5) {
3892 var curve = easyeasy;
3893 easyeasy = function (t) {
3894 return CubicBezierAtTime(t, +curve[1], +curve[2], +curve[3], +curve[4], ms);
3900 timestamp = params.start || anim.start || +new Date;
3904 timestamp: timestamp,
3905 start: timestamp + (anim.del || 0),
3907 initstatus: status || 0,
3915 callback: params.callback,
3918 repeat: times || anim.times,
3919 origin: element.attr(),
3920 totalOrigin: totalOrigin
3922 animationElements.push(e);
3923 if (status && !isInAnim && !isInAnimSet) {
3925 e.start = new Date - ms * status;
3926 if (animationElements.length == 1) {
3931 e.start = new Date - e.ms * status;
3933 animationElements.length == 1 && requestAnimFrame(animation);
3935 isInAnim.initstatus = status;
3936 isInAnim.start = new Date - isInAnim.ms * status;
3938 eve("anim.start." + element.id, element, anim);
3944 * Creates an animation object that can be passed to the @Element.animate or @Element.animateWith methods.
3945 * See also @Animation.delay and @Animation.repeat methods.
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 = (object) @Animation
3956 R.animation = function (params, ms, easing, callback) {
3957 if (params instanceof Animation) {
3960 if (R.is(easing, "function") || !easing) {
3961 callback = callback || easing || null;
3964 params = Object(params);
3969 for (attr in params) if (params[has](attr) && toFloat(attr) != attr && toFloat(attr) + "%" != attr) {
3971 p[attr] = params[attr];
3974 return new Animation(params, ms);
3976 easing && (p.easing = easing);
3977 callback && (p.callback = callback);
3978 return new Animation({100: p}, ms);
3985 * Creates and starts animation for given element.
3989 - params (object) final attributes for the element, see also @Element.attr
3990 - ms (number) number of milliseconds for animation to run
3991 - easing (string) #optional easing type. Accept one of @Raphael.easing_formulas or CSS format: `cubic‐bezier(XX, XX, XX, XX)`
3992 - callback (function) #optional callback function. Will be called at the end of animation.
3994 - animation (object) animation object, see @Raphael.animation
3996 = (object) original element
3998 elproto.animate = function (params, ms, easing, callback) {
4000 if (element.removed) {
4001 callback && callback.call(element);
4004 var anim = params instanceof Animation ? params : R.animation(params, ms, easing, callback);
4005 runAnimation(anim, element, anim.percents[0], null, element.attr());
4012 * Sets the status of animation of the element in milliseconds. Similar to @Element.status method.
4016 - anim (object) animation object
4017 - value (number) number of milliseconds from the beginning of the animation
4019 = (object) original element if `value` is specified
4020 * Note, that during animation following events are triggered:
4022 * On each animation frame event `anim.frame.<id>`, on start `anim.start.<id>` and on end `anim.finish.<id>`.
4024 elproto.setTime = function (anim, value) {
4025 if (anim && value != null) {
4026 this.status(anim, mmin(value, anim.ms) / anim.ms);
4034 * Gets or sets the status of animation of the element.
4038 - anim (object) #optional animation object
4039 - 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.
4043 = (array) status if `anim` is not specified. Array of objects in format:
4045 o anim: (object) animation object
4046 o status: (number) status
4049 = (object) original element if `value` is specified
4051 elproto.status = function (anim, value) {
4056 if (value != null) {
4057 runAnimation(anim, this, -1, mmin(value, 1));
4060 len = animationElements.length;
4061 for (; i < len; i++) {
4062 e = animationElements[i];
4063 if (e.el.id == this.id && (!anim || e.anim == anim)) {
4083 * Stops animation of the element with ability to resume it later on.
4087 - anim (object) #optional animation object
4089 = (object) original element
4091 elproto.pause = function (anim) {
4092 for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) {
4093 if (eve("anim.pause." + this.id, this, animationElements[i].anim) !== false) {
4094 animationElements[i].paused = true;
4103 * Resumes animation if it was paused with @Element.pause method.
4107 - anim (object) #optional animation object
4109 = (object) original element
4111 elproto.resume = function (anim) {
4112 for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) {
4113 var e = animationElements[i];
4114 if (eve("anim.resume." + this.id, this, e.anim) !== false) {
4116 this.status(e.anim, e.status);
4125 * Stops animation of the element.
4129 - anim (object) #optional animation object
4131 = (object) original element
4133 elproto.stop = function (anim) {
4134 for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) {
4135 if (eve("anim.stop." + this.id, this, animationElements[i].anim) !== false) {
4136 animationElements.splice(i--, 1);
4141 elproto.toString = function () {
4142 return "Rapha\xebl\u2019s object";
4146 var Set = function (items) {
4151 for (var i = 0, ii = items.length; i < ii; i++) {
4152 if (items[i] && (items[i].constructor == elproto.constructor || items[i].constructor == Set)) {
4153 this[this.items.length] = this.items[this.items.length] = items[i];
4159 setproto = Set.prototype;
4164 * Adds each argument to the current set.
4165 = (object) original element
4167 setproto.push = function () {
4170 for (var i = 0, ii = arguments.length; i < ii; i++) {
4171 item = arguments[i];
4172 if (item && (item.constructor == elproto.constructor || item.constructor == Set)) {
4173 len = this.items.length;
4174 this[len] = this.items[len] = item;
4184 * Removes last element and returns it.
4187 setproto.pop = function () {
4188 this.length && delete this[this.length--];
4189 return this.items.pop();
4195 * Executes given function for each element in the set.
4197 * If function returns `false` it will stop loop running.
4201 - callback (function) function to run
4202 - thisArg (object) context object for the callback
4203 = (object) Set object
4205 setproto.forEach = function (callback, thisArg) {
4206 for (var i = 0, ii = this.items.length; i < ii; i++) {
4207 if (callback.call(thisArg, this.items[i], i) === false) {
4213 for (var method in elproto) if (elproto[has](method)) {
4214 setproto[method] = (function (methodname) {
4215 return function () {
4216 var arg = arguments;
4217 return this.forEach(function (el) {
4218 el[methodname][apply](el, arg);
4223 setproto.attr = function (name, value) {
4224 if (name && R.is(name, array) && R.is(name[0], "object")) {
4225 for (var j = 0, jj = name.length; j < jj; j++) {
4226 this.items[j].attr(name[j]);
4229 for (var i = 0, ii = this.items.length; i < ii; i++) {
4230 this.items[i].attr(name, value);
4239 * Removeds all elements from the set
4241 setproto.clear = function () {
4242 while (this.length) {
4250 * Removes given element from the set
4254 - index (number) position of the deletion
4255 - count (number) number of element to remove
4256 - insertion… (object) #optional elements to insert
4257 = (object) set elements that were deleted
4259 setproto.splice = function (index, count, insertion) {
4260 index = index < 0 ? mmax(this.length + index, 0) : index;
4261 count = mmax(0, mmin(this.length - index, count));
4266 for (i = 2; i < arguments.length; i++) {
4267 args.push(arguments[i]);
4269 for (i = 0; i < count; i++) {
4270 todel.push(this[index + i]);
4272 for (; i < this.length - index; i++) {
4273 tail.push(this[index + i]);
4275 var arglen = args.length;
4276 for (i = 0; i < arglen + tail.length; i++) {
4277 this.items[index + i] = this[index + i] = i < arglen ? args[i] : tail[i - arglen];
4279 i = this.items.length = this.length -= count - arglen;
4283 return new Set(todel);
4289 * Removes given element from the set
4293 - element (object) element to remove
4294 = (boolean) `true` if object was found & removed from the set
4296 setproto.exclude = function (el) {
4297 for (var i = 0, ii = this.length; i < ii; i++) if (this[i] == el) {
4302 setproto.animate = function (params, ms, easing, callback) {
4303 (R.is(easing, "function") || !easing) && (callback = easing || null);
4304 var len = this.items.length,
4312 callback && (collector = function () {
4313 !--len && callback.call(set);
4315 easing = R.is(easing, string) ? easing : collector;
4316 var anim = R.animation(params, ms, easing, collector);
4317 item = this.items[--i].animate(anim);
4319 this.items[i] && !this.items[i].removed && this.items[i].animateWith(item, anim);
4323 setproto.insertAfter = function (el) {
4324 var i = this.items.length;
4326 this.items[i].insertAfter(el);
4330 setproto.getBBox = function () {
4335 for (var i = this.items.length; i--;) if (!this.items[i].removed) {
4336 var box = this.items[i].getBBox();
4339 w.push(box.x + box.width);
4340 h.push(box.y + box.height);
4342 x = mmin[apply](0, x);
4343 y = mmin[apply](0, y);
4347 width: mmax[apply](0, w) - x,
4348 height: mmax[apply](0, h) - y
4351 setproto.clone = function (s) {
4353 for (var i = 0, ii = this.items.length; i < ii; i++) {
4354 s.push(this.items[i].clone());
4358 setproto.toString = function () {
4359 return "Rapha\xebl\u2018s set";
4363 * Raphael.registerFont
4366 * 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.
4367 * Returns original parameter, so it could be used with chaining.
4368 # <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>
4372 - font (object) the font to register
4373 = (object) the font you passed in
4375 | Cufon.registerFont(Raphael.registerFont({…}));
4377 R.registerFont = function (font) {
4381 this.fonts = this.fonts || {};
4387 family = font.face["font-family"];
4388 for (var prop in font.face) if (font.face[has](prop)) {
4389 fontcopy.face[prop] = font.face[prop];
4391 if (this.fonts[family]) {
4392 this.fonts[family].push(fontcopy);
4394 this.fonts[family] = [fontcopy];
4397 fontcopy.face["units-per-em"] = toInt(font.face["units-per-em"], 10);
4398 for (var glyph in font.glyphs) if (font.glyphs[has](glyph)) {
4399 var path = font.glyphs[glyph];
4400 fontcopy.glyphs[glyph] = {
4403 d: path.d && "M" + path.d.replace(/[mlcxtrv]/g, function (command) {
4404 return {l: "L", c: "C", x: "z", t: "m", r: "l", v: "c"}[command] || "M";
4408 for (var k in path.k) if (path[has](k)) {
4409 fontcopy.glyphs[glyph].k[k] = path.k[k];
4420 * 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”.
4424 - family (string) font family name or any word from it
4425 - weight (string) #optional font weight
4426 - style (string) #optional font style
4427 - stretch (string) #optional font stretch
4428 = (object) the font object
4430 | paper.print(100, 100, "Test string", paper.getFont("Times", 800), 30);
4432 paperproto.getFont = function (family, weight, style, stretch) {
4433 stretch = stretch || "normal";
4434 style = style || "normal";
4435 weight = +weight || {normal: 400, bold: 700, lighter: 300, bolder: 800}[weight] || 400;
4439 var font = R.fonts[family];
4441 var name = new RegExp("(^|\\s)" + family.replace(/[^\w\d\s+!~.:_-]/g, E) + "(\\s|$)", "i");
4442 for (var fontName in R.fonts) if (R.fonts[has](fontName)) {
4443 if (name.test(fontName)) {
4444 font = R.fonts[fontName];
4451 for (var i = 0, ii = font.length; i < ii; i++) {
4453 if (thefont.face["font-weight"] == weight && (thefont.face["font-style"] == style || !thefont.face["font-style"]) && thefont.face["font-stretch"] == stretch) {
4464 * Creates set of shapes to represent given font at given position with given size.
4465 * Result of the method is set object (see @Paper.set) which contains each letter as separate path object.
4469 - x (number) x position of the text
4470 - y (number) y position of the text
4471 - text (string) text to print
4472 - font (object) font object, see @Paper.getFont
4473 - size (number) #optional size of the font, default is `16`
4474 - origin (string) #optional could be `"baseline"` or `"middle"`, default is `"middle"`
4475 - letter_spacing (number) #optional number in range `-1..1`, default is `0`
4476 = (object) resulting set of letters
4478 | var txt = r.print(10, 50, "print", r.getFont("Museo"), 30).attr({fill: "#fff"});
4479 | // following line will paint first letter in red
4480 | txt[0].attr({fill: "#f00"});
4482 paperproto.print = function (x, y, string, font, size, origin, letter_spacing) {
4483 origin = origin || "middle"; // baseline|middle
4484 letter_spacing = mmax(mmin(letter_spacing || 0, 1), -1);
4485 var out = this.set(),
4486 letters = Str(string)[split](E),
4490 R.is(font, string) && (font = this.getFont(font));
4492 scale = (size || 16) / font.face["units-per-em"];
4493 var bb = font.face.bbox[split](separator),
4495 height = +bb[1] + (origin == "baseline" ? bb[3] - bb[1] + (+font.face.descent) : (bb[3] - bb[1]) / 2);
4496 for (var i = 0, ii = letters.length; i < ii; i++) {
4497 var prev = i && font.glyphs[letters[i - 1]] || {},
4498 curr = font.glyphs[letters[i]];
4499 shift += i ? (prev.w || font.w) + (prev.k && prev.k[letters[i]] || 0) + (font.w * letter_spacing) : 0;
4500 curr && curr.d && out.push(this.path(curr.d).attr({
4503 transform: [["t", shift * scale, 0]]
4506 out.transform(["...s", scale, scale, top, height, "t", (x - top) / scale, (y - height) / scale]);
4515 * Simple format function. Replaces construction of type “`{<number>}`” to the corresponding argument.
4519 - token (string) string to format
4520 - … (string) rest of arguments will be treated as parameters for replacement
4521 = (string) formated string
4527 | // this will draw a rectangular shape equivalent to "M10,20h40v50h-40z"
4528 | paper.path(Raphael.format("M{1},{2}h{3}v{4}h{5}z", x, y, width, height, -width));
4530 R.format = function (token, params) {
4531 var args = R.is(params, array) ? [0][concat](params) : arguments;
4532 token && R.is(token, string) && args.length - 1 && (token = token.replace(formatrg, function (str, i) {
4533 return args[++i] == null ? E : args[i];
4541 * A little bit more advanced format function than @Raphael.format. Replaces construction of type “`{<name>}`” to the corresponding argument.
4545 - token (string) string to format
4546 - json (object) object which properties will be used as a replacement
4547 = (string) formated string
4549 | // this will draw a rectangular shape equivalent to "M10,20h40v50h-40z"
4550 | paper.path(Raphael.format("M{x},{y}h{dim.width}v{dim.height}h{dim['negative width']}z", {
4556 | "negative width": -40
4560 R.fullfill = (function () {
4561 var tokenRegex = /\{([^\}]+)\}/g,
4562 objNotationRegex = /(?:(?:^|\.)(.+?)(?=\[|\.|$|\()|\[('|")(.+?)\2\])(\(\))?/g, // matches .xxxxx or ["xxxxx"] to run over object properties
4563 replacer = function (all, key, obj) {
4565 key.replace(objNotationRegex, function (all, name, quote, quotedName, isFunc) {
4566 name = name || quotedName;
4571 typeof res == "function" && isFunc && (res = res());
4574 res = (res == null || res == obj ? all : res) + "";
4577 return function (str, obj) {
4578 return String(str).replace(tokenRegex, function (all, key) {
4579 return replacer(all, key, obj);
4587 * 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.
4588 * Beware, that in this case plugins could stop working, because they are depending on global variable existance.
4590 = (object) Raphael object
4592 | (function (local_raphael) {
4593 | var paper = local_raphael(10, 10, 320, 200);
4595 | })(Raphael.ninja());
4597 R.ninja = function () {
4598 oldRaphael.was ? (g.win.Raphael = oldRaphael.is) : delete Raphael;
4603 [ property (object) ]
4605 * You can add your own method to elements and sets. It is wise to add a set method for each element method
4606 * you added, so you will be able to call the same method on sets too.
4608 * See also @Raphael.el.
4610 | Raphael.el.red = function () {
4611 | this.attr({fill: "#f00"});
4613 | Raphael.st.red = function () {
4614 | this.forEach(function () {
4619 | paper.set(paper.circle(100, 100, 20), paper.circle(110, 100, 20)).red();
4622 // Firefox <3.6 fix: http://webreflection.blogspot.com/2009/11/195-chars-to-help-lazy-loading.html
4623 (function (doc, loaded, f) {
4624 if (doc.readyState == null && doc.addEventListener){
4625 doc.addEventListener(loaded, f = function () {
4626 doc.removeEventListener(loaded, f, false);
4627 doc.readyState = "complete";
4629 doc.readyState = "loading";
4631 function isLoaded() {
4632 (/in/).test(doc.readyState) ? setTimeout(isLoaded, 9) : R.eve("DOMload");
4635 })(document, "DOMContentLoaded");
4637 oldRaphael.was ? (g.win.Raphael = R) : (Raphael = R);
4639 eve.on("DOMload", function () {