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. Please note that you can create your own namespaces
350 * inside the `fn` object — methods will be run in the context of canvas anyway. You should alter
351 * the `fn` object before a Raphaël instance is created, otherwise it will take no effect.
353 | Raphael.fn.arrow = function (x1, y1, x2, y2, size) {
354 | return this.path( ... );
356 | // or create namespace
357 | Raphael.fn.mystuff = {
358 | arrow: function () {…},
359 | star: function () {…},
362 | var paper = Raphael(10, 10, 630, 480);
364 | paper.arrow(10, 10, 30, 30, 5).attr({fill: "#f00"});
365 | paper.mystuff.arrow();
366 | paper.mystuff.star();
368 R.fn = paperproto = Paper.prototype = R.prototype;
375 * Handfull replacement for `typeof` operator.
377 - o (…) any object or primitive
378 - type (string) name of the type, i.e. “string”, “function”, “number”, etc.
379 = (boolean) is given value is of given type
381 R.is = function (o, type) {
382 type = lowerCase.call(type);
383 if (type == "finite") {
384 return !isnan[has](+o);
386 if (type == "array") {
387 return o instanceof Array;
389 return (type == "null" && o === null) ||
390 (type == typeof o && o !== null) ||
391 (type == "object" && o === Object(o)) ||
392 (type == "array" && Array.isArray && Array.isArray(o)) ||
393 objectToString.call(o).slice(8, -1).toLowerCase() == type;
399 * Returns angle between two or three points
401 - x1 (number) x coord of first point
402 - y1 (number) y coord of first point
403 - x2 (number) x coord of second point
404 - y2 (number) y coord of second point
405 - x3 (number) #optional x coord of third point
406 - y3 (number) #optional y coord of third point
407 = (number) angle in degrees.
409 R.angle = function (x1, y1, x2, y2, x3, y3) {
416 return (180 + math.atan2(-y, -x) * 180 / PI + 360) % 360;
418 return R.angle(x1, y1, x3, y3) - R.angle(x2, y2, x3, y3);
425 * Transform angle to radians
427 - deg (number) angle in degrees
428 = (number) angle in radians.
430 R.rad = function (deg) {
431 return deg % 360 * PI / 180;
437 * Transform angle to degrees
439 - deg (number) angle in radians
440 = (number) angle in degrees.
442 R.deg = function (rad) {
443 return rad * 180 / PI % 360;
449 * Snaps given value to given grid.
451 - values (array|number) given array of values or step of the grid
452 - value (number) value to adjust
453 - tolerance (number) #optional tolerance for snapping. Default is `10`.
454 = (number) adjusted value.
456 R.snapTo = function (values, value, tolerance) {
457 tolerance = R.is(tolerance, "finite") ? tolerance : 10;
458 if (R.is(values, array)) {
459 var i = values.length;
460 while (i--) if (abs(values[i] - value) <= tolerance) {
465 var rem = value % values;
466 if (rem < tolerance) {
469 if (rem > values - tolerance) {
470 return value - rem + values;
480 * Returns RFC4122, version 4 ID
482 var createUUID = R.createUUID = (function (uuidRegEx, uuidReplacer) {
484 return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(uuidRegEx, uuidReplacer).toUpperCase();
486 })(/[xy]/g, function (c) {
487 var r = math.random() * 16 | 0,
488 v = c == "x" ? r : (r & 3 | 8);
489 return v.toString(16);
496 * Used when you need to draw in `<iframe>`. Switched window to the iframe one.
498 - newwin (window) new window object
500 R.setWindow = function (newwin) {
501 eve("setWindow", R, g.win, newwin);
503 g.doc = g.win.document;
508 var toHex = function (color) {
510 // http://dean.edwards.name/weblog/2009/10/convert-any-colour-value-to-hex-in-msie/
511 var trim = /^\s+|\s+$/g;
514 var docum = new ActiveXObject("htmlfile");
515 docum.write("<body>");
519 bod = createPopup().document.body;
521 var range = bod.createTextRange();
522 toHex = cacher(function (color) {
524 bod.style.color = Str(color).replace(trim, E);
525 var value = range.queryCommandValue("ForeColor");
526 value = ((value & 255) << 16) | (value & 65280) | ((value & 16711680) >>> 16);
527 return "#" + ("000000" + value.toString(16)).slice(-6);
533 var i = g.doc.createElement("i");
534 i.title = "Rapha\xebl Colour Picker";
535 i.style.display = "none";
536 g.doc.body.appendChild(i);
537 toHex = cacher(function (color) {
538 i.style.color = color;
539 return g.doc.defaultView.getComputedStyle(i, E).getPropertyValue("color");
544 hsbtoString = function () {
545 return "hsb(" + [this.h, this.s, this.b] + ")";
547 hsltoString = function () {
548 return "hsl(" + [this.h, this.s, this.l] + ")";
550 rgbtoString = function () {
553 prepareRGB = function (r, g, b) {
554 if (g == null && R.is(r, "object") && "r" in r && "g" in r && "b" in r) {
559 if (g == null && R.is(r, string)) {
560 var clr = R.getRGB(r);
565 if (r > 1 || g > 1 || b > 1) {
573 packageRGB = function (r, g, b, o) {
582 toString: rgbtoString
584 R.is(o, "finite") && (rgb.opacity = o);
592 * Parses the color string and returns object with all values for the given color.
594 - clr (string) color string in one of the supported formats (see @Raphael.getRGB)
595 = (object) Combined RGB & HSB object in format:
600 o hex (string) color in HTML/CSS format: #••••••,
601 o error (boolean) `true` if string can’t be parsed,
603 o s (number) saturation,
604 o v (number) value (brightness),
605 o l (number) lightness
608 R.color = function (clr) {
610 if (R.is(clr, "object") && "h" in clr && "s" in clr && "b" in clr) {
611 rgb = R.hsb2rgb(clr);
616 } else if (R.is(clr, "object") && "h" in clr && "s" in clr && "l" in clr) {
617 rgb = R.hsl2rgb(clr);
623 if (R.is(clr, "string")) {
626 if (R.is(clr, "object") && "r" in clr && "g" in clr && "b" in clr) {
627 rgb = R.rgb2hsl(clr);
631 rgb = R.rgb2hsb(clr);
635 crl.r = clr.g = clr.b = clr.h = clr.s = clr.v = clr.l = -1;
638 clr.toString = rgbtoString;
645 * Converts HSB values to RGB object.
648 - s (number) saturation
649 - v (number) value or brightness
650 = (object) RGB object in format:
655 o hex (string) color in HTML/CSS format: #••••••
658 R.hsb2rgb = function (h, s, v, o) {
659 if (this.is(h, "object") && "h" in h && "s" in h && "b" in h) {
669 X = C * (1 - abs(h % 2 - 1));
673 R += [C, X, 0, 0, X, C][h];
674 G += [X, C, C, X, 0, 0][h];
675 B += [0, 0, X, C, C, X][h];
676 return packageRGB(R, G, B, o);
682 * Converts HSL values to RGB object.
685 - s (number) saturation
686 - l (number) luminosity
687 = (object) RGB object in format:
692 o hex (string) color in HTML/CSS format: #••••••
695 R.hsl2rgb = function (h, s, l, o) {
696 if (this.is(h, "object") && "h" in h && "s" in h && "l" in h) {
701 if (h > 1 || s > 1 || l > 1) {
709 C = 2 * s * (l < .5 ? l : 1 - l);
710 X = C * (1 - abs(h % 2 - 1));
711 R = G = B = l - C / 2;
714 R += [C, X, 0, 0, X, C][h];
715 G += [X, C, C, X, 0, 0][h];
716 B += [0, 0, X, C, C, X][h];
717 return packageRGB(R, G, B, o);
723 * Converts RGB values to HSB object.
728 = (object) HSB object in format:
731 o s (number) saturation
732 o b (number) brightness
735 R.rgb2hsb = function (r, g, b) {
736 b = prepareRGB(r, g, b);
743 C = V - mmin(r, g, b);
745 V == r ? (g - b) / C :
746 V == g ? (b - r) / C + 2 :
749 H = ((H + 360) % 6) * 60 / 360;
750 S = C == 0 ? 0 : C / V;
751 return {h: H, s: S, b: V, toString: hsbtoString};
757 * Converts RGB values to HSL object.
762 = (object) HSL object in format:
765 o s (number) saturation
766 o l (number) luminosity
769 R.rgb2hsl = function (r, g, b) {
770 b = prepareRGB(r, g, b);
775 var H, S, L, M, m, C;
780 M == r ? (g - b) / C :
781 M == g ? (b - r) / C + 2 :
783 H = ((H + 360) % 6) * 60 / 360;
786 L < .5 ? C / (2 * L) :
788 return {h: H, s: S, l: L, toString: hsltoString};
790 R._path2string = function () {
791 return this.join(",").replace(p2s, "$1");
793 function repush(array, item) {
794 for (var i = 0, ii = array.length; i < ii; i++) if (array[i] === item) {
795 return array.push(array.splice(i, 1)[0]);
798 function cacher(f, scope, postprocessor) {
800 var arg = Array.prototype.slice.call(arguments, 0),
801 args = arg.join("\u2400"),
802 cache = newf.cache = newf.cache || {},
803 count = newf.count = newf.count || [];
804 if (cache[has](args)) {
806 return postprocessor ? postprocessor(cache[args]) : cache[args];
808 count.length >= 1e3 && delete cache[count.shift()];
810 cache[args] = f[apply](scope, arg);
811 return postprocessor ? postprocessor(cache[args]) : cache[args];
816 var preload = R._preload = function (src, f) {
817 var img = g.doc.createElement("img");
818 img.style.cssText = "position:absolute;left:-9999em;top-9999em";
819 img.onload = function () {
822 g.doc.body.removeChild(this);
824 img.onerror = function () {
825 g.doc.body.removeChild(this);
827 g.doc.body.appendChild(img);
831 function clrToString() {
839 * Parses colour string as RGB object
841 - colour (string) colour string in one of formats:
843 # <li>Colour name (“<code>red</code>”, “<code>green</code>”, “<code>cornflowerblue</code>”, etc)</li>
844 # <li>#••• — shortened HTML colour: (“<code>#000</code>”, “<code>#fc0</code>”, etc)</li>
845 # <li>#•••••• — full length HTML colour: (“<code>#000000</code>”, “<code>#bd2300</code>”)</li>
846 # <li>rgb(•••, •••, •••) — red, green and blue channels’ values: (“<code>rgb(200, 100, 0)</code>”)</li>
847 # <li>rgb(•••%, •••%, •••%) — same as above, but in %: (“<code>rgb(100%, 175%, 0%)</code>”)</li>
848 # <li>hsb(•••, •••, •••) — hue, saturation and brightness values: (“<code>hsb(0.5, 0.25, 1)</code>”)</li>
849 # <li>hsb(•••%, •••%, •••%) — same as above, but in %</li>
850 # <li>hsl(•••, •••, •••) — same as hsb</li>
851 # <li>hsl(•••%, •••%, •••%) — same as hsb</li>
853 = (object) RGB object in format:
858 o hex (string) color in HTML/CSS format: #••••••,
859 o error (boolean) true if string can’t be parsed
862 R.getRGB = cacher(function (colour) {
863 if (!colour || !!((colour = Str(colour)).indexOf("-") + 1)) {
864 return {r: -1, g: -1, b: -1, hex: "none", error: 1, toString: clrToString};
866 if (colour == "none") {
867 return {r: -1, g: -1, b: -1, hex: "none", toString: clrToString};
869 !(hsrg[has](colour.toLowerCase().substring(0, 2)) || colour.charAt() == "#") && (colour = toHex(colour));
877 rgb = colour.match(colourRegExp);
880 blue = toInt(rgb[2].substring(5), 16);
881 green = toInt(rgb[2].substring(3, 5), 16);
882 red = toInt(rgb[2].substring(1, 3), 16);
885 blue = toInt((t = rgb[3].charAt(3)) + t, 16);
886 green = toInt((t = rgb[3].charAt(2)) + t, 16);
887 red = toInt((t = rgb[3].charAt(1)) + t, 16);
890 values = rgb[4][split](commaSpaces);
891 red = toFloat(values[0]);
892 values[0].slice(-1) == "%" && (red *= 2.55);
893 green = toFloat(values[1]);
894 values[1].slice(-1) == "%" && (green *= 2.55);
895 blue = toFloat(values[2]);
896 values[2].slice(-1) == "%" && (blue *= 2.55);
897 rgb[1].toLowerCase().slice(0, 4) == "rgba" && (opacity = toFloat(values[3]));
898 values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
901 values = rgb[5][split](commaSpaces);
902 red = toFloat(values[0]);
903 values[0].slice(-1) == "%" && (red *= 2.55);
904 green = toFloat(values[1]);
905 values[1].slice(-1) == "%" && (green *= 2.55);
906 blue = toFloat(values[2]);
907 values[2].slice(-1) == "%" && (blue *= 2.55);
908 (values[0].slice(-3) == "deg" || values[0].slice(-1) == "\xb0") && (red /= 360);
909 rgb[1].toLowerCase().slice(0, 4) == "hsba" && (opacity = toFloat(values[3]));
910 values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
911 return R.hsb2rgb(red, green, blue, opacity);
914 values = rgb[6][split](commaSpaces);
915 red = toFloat(values[0]);
916 values[0].slice(-1) == "%" && (red *= 2.55);
917 green = toFloat(values[1]);
918 values[1].slice(-1) == "%" && (green *= 2.55);
919 blue = toFloat(values[2]);
920 values[2].slice(-1) == "%" && (blue *= 2.55);
921 (values[0].slice(-3) == "deg" || values[0].slice(-1) == "\xb0") && (red /= 360);
922 rgb[1].toLowerCase().slice(0, 4) == "hsla" && (opacity = toFloat(values[3]));
923 values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
924 return R.hsl2rgb(red, green, blue, opacity);
926 rgb = {r: red, g: green, b: blue, toString: clrToString};
927 rgb.hex = "#" + (16777216 | blue | (green << 8) | (red << 16)).toString(16).slice(1);
928 R.is(opacity, "finite") && (rgb.opacity = opacity);
931 return {r: -1, g: -1, b: -1, hex: "none", error: 1, toString: clrToString};
937 * Converts HSB values to hex representation of the colour.
940 - s (number) saturation
941 - b (number) value or brightness
942 = (string) hex representation of the colour.
944 R.hsb = cacher(function (h, s, b) {
945 return R.hsb2rgb(h, s, b).hex;
951 * Converts HSL values to hex representation of the colour.
954 - s (number) saturation
955 - l (number) luminosity
956 = (string) hex representation of the colour.
958 R.hsl = cacher(function (h, s, l) {
959 return R.hsl2rgb(h, s, l).hex;
965 * Converts RGB values to hex representation of the colour.
970 = (string) hex representation of the colour.
972 R.rgb = cacher(function (r, g, b) {
973 return "#" + (16777216 | b | (g << 8) | (r << 16)).toString(16).slice(1);
979 * On each call returns next colour in the spectrum. To reset it back to red call @Raphael.getColor.reset
981 - value (number) #optional brightness, default is `0.75`
982 = (string) hex representation of the colour.
984 R.getColor = function (value) {
985 var start = this.getColor.start = this.getColor.start || {h: 0, s: 1, b: value || .75},
986 rgb = this.hsb2rgb(start.h, start.s, start.b);
991 start.s <= 0 && (this.getColor.start = {h: 0, s: 1, b: start.b});
996 * Raphael.getColor.reset
999 * Resets spectrum position for @Raphael.getColor back to red.
1001 R.getColor.reset = function () {
1005 // http://schepers.cc/getting-to-the-point
1006 function catmullRom2bezier(crp) {
1008 for (var i = 0, iLen = crp.length; iLen - 2 > i; i += 2) {
1009 var p = [{x: +crp[i], y: +crp[i + 1]},
1010 {x: +crp[i], y: +crp[i + 1]},
1011 {x: +crp[i + 2], y: +crp[i + 3]},
1012 {x: +crp[i + 4], y: +crp[i + 5]}];
1013 if (iLen - 4 == i) {
1014 p[0] = {x: +crp[i - 2], y: +crp[i - 1]};
1017 p[0] = {x: +crp[i - 2], y: +crp[i - 1]};
1020 (-p[0].x + 6 * p[1].x + p[2].x) / 6,
1021 (-p[0].y + 6 * p[1].y + p[2].y) / 6,
1022 (p[1].x + 6 * p[2].x - p[3].x) / 6,
1023 (p[1].y + 6*p[2].y - p[3].y) / 6,
1032 * Raphael.parsePathString
1037 * Parses given path string into an array of arrays of path segments.
1039 - pathString (string|array) path string or array of segments (in the last case it will be returned straight away)
1040 = (array) array of segments.
1042 R.parsePathString = cacher(function (pathString) {
1046 var paramCounts = {a: 7, c: 6, h: 1, l: 2, m: 2, r: 4, q: 4, s: 4, t: 2, v: 1, z: 0},
1048 if (R.is(pathString, array) && R.is(pathString[0], array)) { // rough assumption
1049 data = pathClone(pathString);
1052 Str(pathString).replace(pathCommand, function (a, b, c) {
1054 name = b.toLowerCase();
1055 c.replace(pathValues, function (a, b) {
1056 b && params.push(+b);
1058 if (name == "m" && params.length > 2) {
1059 data.push([b][concat](params.splice(0, 2)));
1061 b = b == "m" ? "l" : "L";
1064 data.push([b][concat](params));
1065 } else while (params.length >= paramCounts[name]) {
1066 data.push([b][concat](params.splice(0, paramCounts[name])));
1067 if (!paramCounts[name]) {
1073 data.toString = R._path2string;
1077 * Raphael.parseTransformString
1082 * Parses given path string into an array of transformations.
1084 - TString (string|array) transform string or array of transformations (in the last case it will be returned straight away)
1085 = (array) array of transformations.
1087 R.parseTransformString = cacher(function (TString) {
1091 var paramCounts = {r: 3, s: 4, t: 2, m: 6},
1093 if (R.is(TString, array) && R.is(TString[0], array)) { // rough assumption
1094 data = pathClone(TString);
1097 Str(TString).replace(tCommand, function (a, b, c) {
1099 name = lowerCase.call(b);
1100 c.replace(pathValues, function (a, b) {
1101 b && params.push(+b);
1103 data.push([b][concat](params));
1106 data.toString = R._path2string;
1110 * Raphael.findDotsAtSegment
1115 * Find dot coordinates on the given cubic bezier curve at the given t.
1117 - p1x (number) x of the first point of the curve
1118 - p1y (number) y of the first point of the curve
1119 - c1x (number) x of the first anchor of the curve
1120 - c1y (number) y of the first anchor of the curve
1121 - c2x (number) x of the second anchor of the curve
1122 - c2y (number) y of the second anchor of the curve
1123 - p2x (number) x of the second point of the curve
1124 - p2y (number) y of the second point of the curve
1125 - t (number) position on the curve (0..1)
1126 = (object) point information in format:
1128 o x: (number) x coordinate of the point
1129 o y: (number) y coordinate of the point
1131 o x: (number) x coordinate of the left anchor
1132 o y: (number) y coordinate of the left anchor
1135 o x: (number) x coordinate of the right anchor
1136 o y: (number) y coordinate of the right anchor
1139 o x: (number) x coordinate of the start of the curve
1140 o y: (number) y coordinate of the start of the curve
1143 o x: (number) x coordinate of the end of the curve
1144 o y: (number) y coordinate of the end of the curve
1146 o alpha: (number) angle of the curve derivative at the point
1149 R.findDotsAtSegment = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) {
1155 x = t13 * p1x + t12 * 3 * t * c1x + t1 * 3 * t * t * c2x + t3 * p2x,
1156 y = t13 * p1y + t12 * 3 * t * c1y + t1 * 3 * t * t * c2y + t3 * p2y,
1157 mx = p1x + 2 * t * (c1x - p1x) + t2 * (c2x - 2 * c1x + p1x),
1158 my = p1y + 2 * t * (c1y - p1y) + t2 * (c2y - 2 * c1y + p1y),
1159 nx = c1x + 2 * t * (c2x - c1x) + t2 * (p2x - 2 * c2x + c1x),
1160 ny = c1y + 2 * t * (c2y - c1y) + t2 * (p2y - 2 * c2y + c1y),
1161 ax = t1 * p1x + t * c1x,
1162 ay = t1 * p1y + t * c1y,
1163 cx = t1 * c2x + t * p2x,
1164 cy = t1 * c2y + t * p2y,
1165 alpha = (90 - math.atan2(mx - nx, my - ny) * 180 / PI);
1166 (mx > nx || my < ny) && (alpha += 180);
1172 start: {x: ax, y: ay},
1173 end: {x: cx, y: cy},
1177 var pathDimensions = cacher(function (path) {
1179 return {x: 0, y: 0, width: 0, height: 0};
1181 path = path2curve(path);
1187 for (var i = 0, ii = path.length; i < ii; i++) {
1195 var dim = curveDim(x, y, p[1], p[2], p[3], p[4], p[5], p[6]);
1196 X = X[concat](dim.min.x, dim.max.x);
1197 Y = Y[concat](dim.min.y, dim.max.y);
1202 var xmin = mmin[apply](0, X),
1203 ymin = mmin[apply](0, Y);
1207 width: mmax[apply](0, X) - xmin,
1208 height: mmax[apply](0, Y) - ymin
1210 }, null, function (o) {
1218 pathClone = function (pathArray) {
1220 if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) { // rough assumption
1221 pathArray = R.parsePathString(pathArray);
1223 for (var i = 0, ii = pathArray.length; i < ii; i++) {
1225 for (var j = 0, jj = pathArray[i].length; j < jj; j++) {
1226 res[i][j] = pathArray[i][j];
1229 res.toString = R._path2string;
1232 pathToRelative = R._pathToRelative = cacher(function (pathArray) {
1233 if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) { // rough assumption
1234 pathArray = R.parsePathString(pathArray);
1242 if (pathArray[0][0] == "M") {
1243 x = pathArray[0][1];
1244 y = pathArray[0][2];
1248 res.push(["M", x, y]);
1250 for (var i = start, ii = pathArray.length; i < ii; i++) {
1251 var r = res[i] = [],
1253 if (pa[0] != lowerCase.call(pa[0])) {
1254 r[0] = lowerCase.call(pa[0]);
1262 r[6] = +(pa[6] - x).toFixed(3);
1263 r[7] = +(pa[7] - y).toFixed(3);
1266 r[1] = +(pa[1] - y).toFixed(3);
1272 for (var j = 1, jj = pa.length; j < jj; j++) {
1273 r[j] = +(pa[j] - ((j % 2) ? x : y)).toFixed(3);
1282 for (var k = 0, kk = pa.length; k < kk; k++) {
1286 var len = res[i].length;
1287 switch (res[i][0]) {
1293 x += +res[i][len - 1];
1296 y += +res[i][len - 1];
1299 x += +res[i][len - 2];
1300 y += +res[i][len - 1];
1303 res.toString = R._path2string;
1306 pathToAbsolute = R._pathToAbsolute = cacher(function (pathArray) {
1307 if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) { // rough assumption
1308 pathArray = R.parsePathString(pathArray);
1310 if (!pathArray || !pathArray.length) {
1311 return [["M", 0, 0]];
1319 if (pathArray[0][0] == "M") {
1320 x = +pathArray[0][1];
1321 y = +pathArray[0][2];
1325 res[0] = ["M", x, y];
1327 for (var r, pa, i = start, ii = pathArray.length; i < ii; i++) {
1330 if (pa[0] != upperCase.call(pa[0])) {
1331 r[0] = upperCase.call(pa[0]);
1339 r[6] = +(pa[6] + x);
1340 r[7] = +(pa[7] + y);
1349 var dots = [x, y][concat](pa.slice(1));
1350 for (var j = 2, jj = dots.length; j < jj; j++) {
1351 dots[j] = +dots[j] + x;
1352 dots[++j] = +dots[j] + y;
1355 res = res[concat](catmullRom2bezier(dots));
1361 for (j = 1, jj = pa.length; j < jj; j++) {
1362 r[j] = +pa[j] + ((j % 2) ? x : y);
1365 } else if (pa[0] == "R") {
1366 dots = [x, y][concat](pa.slice(1));
1368 res = res[concat](catmullRom2bezier(dots));
1369 r = ["R"][concat](pa.slice(-2));
1371 for (var k = 0, kk = pa.length; k < kk; k++) {
1387 mx = r[r.length - 2];
1388 my = r[r.length - 1];
1390 x = r[r.length - 2];
1391 y = r[r.length - 1];
1394 res.toString = R._path2string;
1396 }, null, pathClone),
1397 l2c = function (x1, y1, x2, y2) {
1398 return [x1, y1, x2, y2, x2, y2];
1400 q2c = function (x1, y1, ax, ay, x2, y2) {
1404 _13 * x1 + _23 * ax,
1405 _13 * y1 + _23 * ay,
1406 _13 * x2 + _23 * ax,
1407 _13 * y2 + _23 * ay,
1412 a2c = function (x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursive) {
1413 // for more information of where this math came from visit:
1414 // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
1415 var _120 = PI * 120 / 180,
1416 rad = PI / 180 * (+angle || 0),
1419 rotate = cacher(function (x, y, rad) {
1420 var X = x * math.cos(rad) - y * math.sin(rad),
1421 Y = x * math.sin(rad) + y * math.cos(rad);
1422 return {x: X, y: Y};
1425 xy = rotate(x1, y1, -rad);
1428 xy = rotate(x2, y2, -rad);
1431 var cos = math.cos(PI / 180 * angle),
1432 sin = math.sin(PI / 180 * angle),
1435 var h = (x * x) / (rx * rx) + (y * y) / (ry * ry);
1443 k = (large_arc_flag == sweep_flag ? -1 : 1) *
1444 math.sqrt(abs((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x))),
1445 cx = k * rx * y / ry + (x1 + x2) / 2,
1446 cy = k * -ry * x / rx + (y1 + y2) / 2,
1447 f1 = math.asin(((y1 - cy) / ry).toFixed(9)),
1448 f2 = math.asin(((y2 - cy) / ry).toFixed(9));
1450 f1 = x1 < cx ? PI - f1 : f1;
1451 f2 = x2 < cx ? PI - f2 : f2;
1452 f1 < 0 && (f1 = PI * 2 + f1);
1453 f2 < 0 && (f2 = PI * 2 + f2);
1454 if (sweep_flag && f1 > f2) {
1457 if (!sweep_flag && f2 > f1) {
1467 if (abs(df) > _120) {
1471 f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1);
1472 x2 = cx + rx * math.cos(f2);
1473 y2 = cy + ry * math.sin(f2);
1474 res = a2c(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [f2, f2old, cx, cy]);
1477 var c1 = math.cos(f1),
1481 t = math.tan(df / 4),
1482 hx = 4 / 3 * rx * t,
1483 hy = 4 / 3 * ry * t,
1485 m2 = [x1 + hx * s1, y1 - hy * c1],
1486 m3 = [x2 + hx * s2, y2 - hy * c2],
1488 m2[0] = 2 * m1[0] - m2[0];
1489 m2[1] = 2 * m1[1] - m2[1];
1491 return [m2, m3, m4][concat](res);
1493 res = [m2, m3, m4][concat](res).join()[split](",");
1495 for (var i = 0, ii = res.length; i < ii; i++) {
1496 newres[i] = i % 2 ? rotate(res[i - 1], res[i], rad).y : rotate(res[i], res[i + 1], rad).x;
1501 findDotAtSegment = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) {
1504 x: pow(t1, 3) * p1x + pow(t1, 2) * 3 * t * c1x + t1 * 3 * t * t * c2x + pow(t, 3) * p2x,
1505 y: pow(t1, 3) * p1y + pow(t1, 2) * 3 * t * c1y + t1 * 3 * t * t * c2y + pow(t, 3) * p2y
1508 curveDim = cacher(function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) {
1509 var a = (c2x - 2 * c1x + p1x) - (p2x - 2 * c2x + c1x),
1510 b = 2 * (c1x - p1x) - 2 * (c2x - c1x),
1512 t1 = (-b + math.sqrt(b * b - 4 * a * c)) / 2 / a,
1513 t2 = (-b - math.sqrt(b * b - 4 * a * c)) / 2 / a,
1517 abs(t1) > "1e12" && (t1 = .5);
1518 abs(t2) > "1e12" && (t2 = .5);
1519 if (t1 > 0 && t1 < 1) {
1520 dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t1);
1524 if (t2 > 0 && t2 < 1) {
1525 dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t2);
1529 a = (c2y - 2 * c1y + p1y) - (p2y - 2 * c2y + c1y);
1530 b = 2 * (c1y - p1y) - 2 * (c2y - c1y);
1532 t1 = (-b + math.sqrt(b * b - 4 * a * c)) / 2 / a;
1533 t2 = (-b - math.sqrt(b * b - 4 * a * c)) / 2 / a;
1534 abs(t1) > "1e12" && (t1 = .5);
1535 abs(t2) > "1e12" && (t2 = .5);
1536 if (t1 > 0 && t1 < 1) {
1537 dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t1);
1541 if (t2 > 0 && t2 < 1) {
1542 dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t2);
1547 min: {x: mmin[apply](0, x), y: mmin[apply](0, y)},
1548 max: {x: mmax[apply](0, x), y: mmax[apply](0, y)}
1551 path2curve = R._path2curve = cacher(function (path, path2) {
1552 var p = pathToAbsolute(path),
1553 p2 = path2 && pathToAbsolute(path2),
1554 attrs = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null},
1555 attrs2 = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null},
1556 processPath = function (path, d) {
1559 return ["C", d.x, d.y, d.x, d.y, d.x, d.y];
1561 !(path[0] in {T:1, Q:1}) && (d.qx = d.qy = null);
1568 path = ["C"][concat](a2c[apply](0, [d.x, d.y][concat](path.slice(1))));
1571 nx = d.x + (d.x - (d.bx || d.x));
1572 ny = d.y + (d.y - (d.by || d.y));
1573 path = ["C", nx, ny][concat](path.slice(1));
1576 d.qx = d.x + (d.x - (d.qx || d.x));
1577 d.qy = d.y + (d.y - (d.qy || d.y));
1578 path = ["C"][concat](q2c(d.x, d.y, d.qx, d.qy, path[1], path[2]));
1583 path = ["C"][concat](q2c(d.x, d.y, path[1], path[2], path[3], path[4]));
1586 path = ["C"][concat](l2c(d.x, d.y, path[1], path[2]));
1589 path = ["C"][concat](l2c(d.x, d.y, path[1], d.y));
1592 path = ["C"][concat](l2c(d.x, d.y, d.x, path[1]));
1595 path = ["C"][concat](l2c(d.x, d.y, d.X, d.Y));
1600 fixArc = function (pp, i) {
1601 if (pp[i].length > 7) {
1605 pp.splice(i++, 0, ["C"][concat](pi.splice(0, 6)));
1608 ii = mmax(p.length, p2 && p2.length || 0);
1611 fixM = function (path1, path2, a1, a2, i) {
1612 if (path1 && path2 && path1[i][0] == "M" && path2[i][0] != "M") {
1613 path2.splice(i, 0, ["M", a2.x, a2.y]);
1618 ii = mmax(p.length, p2 && p2.length || 0);
1621 for (var i = 0, ii = mmax(p.length, p2 && p2.length || 0); i < ii; i++) {
1622 p[i] = processPath(p[i], attrs);
1624 p2 && (p2[i] = processPath(p2[i], attrs2));
1625 p2 && fixArc(p2, i);
1626 fixM(p, p2, attrs, attrs2, i);
1627 fixM(p2, p, attrs2, attrs, i);
1630 seglen = seg.length,
1631 seg2len = p2 && seg2.length;
1632 attrs.x = seg[seglen - 2];
1633 attrs.y = seg[seglen - 1];
1634 attrs.bx = toFloat(seg[seglen - 4]) || attrs.x;
1635 attrs.by = toFloat(seg[seglen - 3]) || attrs.y;
1636 attrs2.bx = p2 && (toFloat(seg2[seg2len - 4]) || attrs2.x);
1637 attrs2.by = p2 && (toFloat(seg2[seg2len - 3]) || attrs2.y);
1638 attrs2.x = p2 && seg2[seg2len - 2];
1639 attrs2.y = p2 && seg2[seg2len - 1];
1641 return p2 ? [p, p2] : p;
1642 }, null, pathClone),
1643 parseDots = R._parseDots = cacher(function (gradient) {
1645 for (var i = 0, ii = gradient.length; i < ii; i++) {
1647 par = gradient[i].match(/^([^:]*):?([\d\.]*)/);
1648 dot.color = R.getRGB(par[1]);
1649 if (dot.color.error) {
1652 dot.color = dot.color.hex;
1653 par[2] && (dot.offset = par[2] + "%");
1656 for (i = 1, ii = dots.length - 1; i < ii; i++) {
1657 if (!dots[i].offset) {
1658 var start = toFloat(dots[i - 1].offset || 0),
1660 for (var j = i + 1; j < ii; j++) {
1661 if (dots[j].offset) {
1662 end = dots[j].offset;
1671 var d = (end - start) / (j - i + 1);
1672 for (; i < j; i++) {
1674 dots[i].offset = start + "%";
1680 tear = R._tear = function (el, paper) {
1681 el == paper.top && (paper.top = el.prev);
1682 el == paper.bottom && (paper.bottom = el.next);
1683 el.next && (el.next.prev = el.prev);
1684 el.prev && (el.prev.next = el.next);
1686 tofront = R._tofront = function (el, paper) {
1687 if (paper.top === el) {
1692 el.prev = paper.top;
1693 paper.top.next = el;
1696 toback = R._toback = function (el, paper) {
1697 if (paper.bottom === el) {
1701 el.next = paper.bottom;
1703 paper.bottom.prev = el;
1706 insertafter = R._insertafter = function (el, el2, paper) {
1708 el2 == paper.top && (paper.top = el);
1709 el2.next && (el2.next.prev = el);
1714 insertbefore = R._insertbefore = function (el, el2, paper) {
1716 el2 == paper.bottom && (paper.bottom = el);
1717 el2.prev && (el2.prev.next = el);
1722 removed = function (methodname) {
1723 return function () {
1724 throw new Error("Rapha\xebl: you are calling to method \u201c" + methodname + "\u201d of removed object");
1727 extractTransform = R._extractTransform = function (el, tstr) {
1729 return el._.transform;
1731 tstr = Str(tstr).replace(/\.{3}|\u2026/g, el._.transform || E);
1732 var tdata = R.parseTransformString(tstr),
1740 _.transform = tdata || [];
1742 for (var i = 0, ii = tdata.length; i < ii; i++) {
1745 command = Str(t[0]).toLowerCase(),
1746 absolute = t[0] != command,
1747 inver = absolute ? m.invert() : 0,
1753 if (command == "t" && tlen == 3) {
1757 x2 = inver.x(t[1], t[2]);
1758 y2 = inver.y(t[1], t[2]);
1759 m.translate(x2 - x1, y2 - y1);
1761 m.translate(t[1], t[2]);
1763 } else if (command == "r") {
1765 bb = bb || el.getBBox(1);
1766 m.rotate(t[1], bb.x + bb.width / 2, bb.y + bb.height / 2);
1768 } else if (tlen == 4) {
1770 x2 = inver.x(t[2], t[3]);
1771 y2 = inver.y(t[2], t[3]);
1772 m.rotate(t[1], x2, y2);
1774 m.rotate(t[1], t[2], t[3]);
1778 } else if (command == "s") {
1779 if (tlen == 2 || tlen == 3) {
1780 bb = bb || el.getBBox(1);
1781 m.scale(t[1], t[tlen - 1], bb.x + bb.width / 2, bb.y + bb.height / 2);
1784 } else if (tlen == 5) {
1786 x2 = inver.x(t[3], t[4]);
1787 y2 = inver.y(t[3], t[4]);
1788 m.scale(t[1], t[2], x2, y2);
1790 m.scale(t[1], t[2], t[3], t[4]);
1795 } else if (command == "m" && tlen == 7) {
1796 m.add(t[1], t[2], t[3], t[4], t[5], t[6]);
1811 if (sx == 1 && sy == 1 && !deg && _.bbox) {
1818 getEmpty = function (item) {
1820 switch (l.toLowerCase()) {
1821 case "t": return [l, 0, 0];
1822 case "m": return [l, 1, 0, 0, 1, 0, 0];
1823 case "r": if (item.length == 4) {
1824 return [l, 0, item[2], item[3]];
1828 case "s": if (item.length == 5) {
1829 return [l, 1, 1, item[3], item[4]];
1830 } else if (item.length == 3) {
1837 equaliseTransform = R._equaliseTransform = function (t1, t2) {
1838 t2 = Str(t2).replace(/\.{3}|\u2026/g, t1);
1839 t1 = R.parseTransformString(t1) || [];
1840 t2 = R.parseTransformString(t2) || [];
1841 var maxlength = mmax(t1.length, t2.length),
1846 for (; i < maxlength; i++) {
1847 tt1 = t1[i] || getEmpty(t2[i]);
1848 tt2 = t2[i] || getEmpty(tt1);
1849 if ((tt1[0] != tt2[0]) ||
1850 (tt1[0].toLowerCase() == "r" && (tt1[2] != tt2[2] || tt1[3] != tt2[3])) ||
1851 (tt1[0].toLowerCase() == "s" && (tt1[3] != tt2[3] || tt1[4] != tt2[4]))
1857 for (j = 0, jj = mmax(tt1.length, tt2.length); j < jj; j++) {
1858 j in tt1 && (from[i][j] = tt1[j]);
1859 j in tt2 && (to[i][j] = tt2[j]);
1867 R._getContainer = function (x, y, w, h) {
1869 container = h == null && !R.is(x, "object") ? g.doc.getElementById(x) : x;
1870 if (container == null) {
1873 if (container.tagName) {
1876 container: container,
1877 width: container.style.pixelWidth || container.offsetWidth,
1878 height: container.style.pixelHeight || container.offsetHeight
1882 container: container,
1897 * Raphael.pathToRelative
1902 * Converts path to relative form
1904 - pathString (string|array) path string or array of segments
1905 = (array) array of segments.
1907 R.pathToRelative = pathToRelative;
1910 * Raphael.path2curve
1915 * Converts path to a new path where all segments are cubic bezier curves.
1917 - pathString (string|array) path string or array of segments
1918 = (array) array of segments.
1920 R.path2curve = path2curve;
1927 * Returns matrix based on given parameters.
1937 R.matrix = function (a, b, c, d, e, f) {
1938 return new Matrix(a, b, c, d, e, f);
1940 function Matrix(a, b, c, d, e, f) {
1957 (function (matrixproto) {
1962 * Adds given matrix to existing one.
1971 - matrix (object) @Matrix
1973 matrixproto.add = function (a, b, c, d, e, f) {
1974 var out = [[], [], []],
1975 m = [[this.a, this.c, this.e], [this.b, this.d, this.f], [0, 0, 1]],
1976 matrix = [[a, c, e], [b, d, f], [0, 0, 1]],
1979 if (a && a instanceof Matrix) {
1980 matrix = [[a.a, a.c, a.e], [a.b, a.d, a.f], [0, 0, 1]];
1983 for (x = 0; x < 3; x++) {
1984 for (y = 0; y < 3; y++) {
1986 for (z = 0; z < 3; z++) {
1987 res += m[x][z] * matrix[z][y];
2003 * Returns inverted version of the matrix
2006 matrixproto.invert = function () {
2008 x = me.a * me.d - me.b * me.c;
2009 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);
2015 * Returns copy of the matrix
2018 matrixproto.clone = function () {
2019 return new Matrix(this.a, this.b, this.c, this.d, this.e, this.f);
2025 * Translate the matrix
2030 matrixproto.translate = function (x, y) {
2031 this.add(1, 0, 0, 1, x, y);
2040 - y (number) #optional
2041 - cx (number) #optional
2042 - cy (number) #optional
2044 matrixproto.scale = function (x, y, cx, cy) {
2045 y == null && (y = x);
2046 (cx || cy) && this.add(1, 0, 0, 1, cx, cy);
2047 this.add(x, 0, 0, y, 0, 0);
2048 (cx || cy) && this.add(1, 0, 0, 1, -cx, -cy);
2054 * Rotates the matrix
2060 matrixproto.rotate = function (a, x, y) {
2064 var cos = +math.cos(a).toFixed(9),
2065 sin = +math.sin(a).toFixed(9);
2066 this.add(cos, sin, -sin, cos, x, y);
2067 this.add(1, 0, 0, 1, -x, -y);
2073 * Return x coordinate for given point after transformation described by the matrix. See also @Matrix.y
2079 matrixproto.x = function (x, y) {
2080 return x * this.a + y * this.c + this.e;
2086 * Return y coordinate for given point after transformation described by the matrix. See also @Matrix.x
2092 matrixproto.y = function (x, y) {
2093 return x * this.b + y * this.d + this.f;
2095 matrixproto.get = function (i) {
2096 return +this[Str.fromCharCode(97 + i)].toFixed(4);
2098 matrixproto.toString = function () {
2100 "matrix(" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)].join() + ")" :
2101 [this.get(0), this.get(2), this.get(1), this.get(3), 0, 0].join();
2103 matrixproto.toFilter = function () {
2104 return "progid:DXImageTransform.Microsoft.Matrix(M11=" + this.get(0) +
2105 ", M12=" + this.get(2) + ", M21=" + this.get(1) + ", M22=" + this.get(3) +
2106 ", Dx=" + this.get(4) + ", Dy=" + this.get(5) + ", sizingmethod='auto expand')";
2108 matrixproto.offset = function () {
2109 return [this.e.toFixed(4), this.f.toFixed(4)];
2112 return a[0] * a[0] + a[1] * a[1];
2114 function normalize(a) {
2115 var mag = math.sqrt(norm(a));
2116 a[0] && (a[0] /= mag);
2117 a[1] && (a[1] /= mag);
2123 * Splits matrix into primitive transformations
2124 = (object) in format:
2125 o dx (number) translation by x
2126 o dy (number) translation by y
2127 o scalex (number) scale by x
2128 o scaley (number) scale by y
2129 o shear (number) shear
2130 o rotate (number) rotation in deg
2131 o isSimple (boolean) could it be represented via simple transformations
2133 matrixproto.split = function () {
2140 var row = [[this.a, this.c], [this.b, this.d]];
2141 out.scalex = math.sqrt(norm(row[0]));
2144 out.shear = row[0][0] * row[1][0] + row[0][1] * row[1][1];
2145 row[1] = [row[1][0] - row[0][0] * out.shear, row[1][1] - row[0][1] * out.shear];
2147 out.scaley = math.sqrt(norm(row[1]));
2149 out.shear /= out.scaley;
2152 var sin = -row[0][1],
2155 out.rotate = R.deg(math.acos(cos));
2157 out.rotate = 360 - out.rotate;
2160 out.rotate = R.deg(math.asin(sin));
2163 out.isSimple = !+out.shear.toFixed(9) && (out.scalex.toFixed(9) == out.scaley.toFixed(9) || !out.rotate);
2164 out.isSuperSimple = !+out.shear.toFixed(9) && out.scalex.toFixed(9) == out.scaley.toFixed(9) && !out.rotate;
2165 out.noRotation = !+out.shear.toFixed(9) && !out.rotate;
2169 * Matrix.toTransformString
2172 * Return transform string that represents given matrix
2173 = (string) transform string
2175 matrixproto.toTransformString = function (shorter) {
2176 var s = shorter || this[split]();
2178 return "t" + [s.dx, s.dy] + "s" + [s.scalex, s.scaley, 0, 0] + "r" + [s.rotate, 0, 0];
2180 return "m" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)];
2183 })(Matrix.prototype);
2185 // WebKit rendering bug workaround method
2186 var version = navigator.userAgent.match(/Version\/(.*?)\s/) || navigator.userAgent.match(/Chrome\/(\d+)/);
2187 if ((navigator.vendor == "Apple Computer, Inc.") && (version && version[1] < 4 || navigator.platform.slice(0, 2) == "iP") ||
2188 (navigator.vendor == "Google Inc." && version && version[1] < 8)) {
2193 * There is an inconvenient rendering bug in Safari (WebKit):
2194 * sometimes the rendering should be forced.
2195 * This method should help with dealing with this bug.
2197 paperproto.safari = function () {
2198 var rect = this.rect(-99, -99, this.width + 99, this.height + 99).attr({stroke: "none"});
2199 setTimeout(function () {rect.remove();});
2202 paperproto.safari = fun;
2205 var preventDefault = function () {
2206 this.returnValue = false;
2208 preventTouch = function () {
2209 return this.originalEvent.preventDefault();
2211 stopPropagation = function () {
2212 this.cancelBubble = true;
2214 stopTouch = function () {
2215 return this.originalEvent.stopPropagation();
2217 addEvent = (function () {
2218 if (g.doc.addEventListener) {
2219 return function (obj, type, fn, element) {
2220 var realName = supportsTouch && touchMap[type] ? touchMap[type] : type,
2222 var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
2223 scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft,
2224 x = e.clientX + scrollX,
2225 y = e.clientY + scrollY;
2226 if (supportsTouch && touchMap[has](type)) {
2227 for (var i = 0, ii = e.targetTouches && e.targetTouches.length; i < ii; i++) {
2228 if (e.targetTouches[i].target == obj) {
2230 e = e.targetTouches[i];
2231 e.originalEvent = olde;
2232 e.preventDefault = preventTouch;
2233 e.stopPropagation = stopTouch;
2238 return fn.call(element, e, x, y);
2240 obj.addEventListener(realName, f, false);
2241 return function () {
2242 obj.removeEventListener(realName, f, false);
2246 } else if (g.doc.attachEvent) {
2247 return function (obj, type, fn, element) {
2248 var f = function (e) {
2249 e = e || g.win.event;
2250 var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
2251 scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft,
2252 x = e.clientX + scrollX,
2253 y = e.clientY + scrollY;
2254 e.preventDefault = e.preventDefault || preventDefault;
2255 e.stopPropagation = e.stopPropagation || stopPropagation;
2256 return fn.call(element, e, x, y);
2258 obj.attachEvent("on" + type, f);
2259 var detacher = function () {
2260 obj.detachEvent("on" + type, f);
2268 dragMove = function (e) {
2271 scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
2272 scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft,
2277 if (supportsTouch) {
2278 var i = e.touches.length,
2281 touch = e.touches[i];
2282 if (touch.identifier == dragi.el._drag.id) {
2285 (e.originalEvent ? e.originalEvent : e).preventDefault();
2292 var node = dragi.el.node,
2294 next = node.nextSibling,
2295 parent = node.parentNode,
2296 display = node.style.display;
2297 g.win.opera && parent.removeChild(node);
2298 node.style.display = "none";
2299 o = dragi.el.paper.getElementByPoint(x, y);
2300 node.style.display = display;
2301 g.win.opera && (next ? parent.insertBefore(node, next) : parent.appendChild(node));
2302 o && eve("drag.over." + dragi.el.id, dragi.el, o);
2305 eve("drag.move." + dragi.el.id, dragi.move_scope || dragi.el, x - dragi.el._drag.x, y - dragi.el._drag.y, x, y, e);
2308 dragUp = function (e) {
2309 R.unmousemove(dragMove).unmouseup(dragUp);
2310 var i = drag.length,
2314 dragi.el._drag = {};
2315 eve("drag.end." + dragi.el.id, dragi.end_scope || dragi.start_scope || dragi.move_scope || dragi.el, e);
2321 [ property (object) ]
2323 * You can add your own method to elements. This is usefull when you want to hack default functionality or
2324 * want to wrap some common transformation or attributes in one method. In difference to canvas methods,
2325 * you can redefine element method at any time. Expending element methods wouldn’t affect set.
2327 | Raphael.el.red = function () {
2328 | this.attr({fill: "#f00"});
2331 | paper.circle(100, 100, 20).red();
2333 elproto = R.el = {};
2338 * Adds event handler for click for the element.
2340 - handler (function) handler for the event
2347 * Removes event handler for click for the element.
2349 - handler (function) handler for the event
2357 * Adds event handler for double click for the element.
2359 - handler (function) handler for the event
2363 * Element.undblclick
2366 * Removes event handler for double click for the element.
2368 - handler (function) handler for the event
2376 * Adds event handler for mousedown for the element.
2378 - handler (function) handler for the event
2382 * Element.unmousedown
2385 * Removes event handler for mousedown for the element.
2387 - handler (function) handler for the event
2395 * Adds event handler for mousemove for the element.
2397 - handler (function) handler for the event
2401 * Element.unmousemove
2404 * Removes event handler for mousemove for the element.
2406 - handler (function) handler for the event
2414 * Adds event handler for mouseout for the element.
2416 - handler (function) handler for the event
2420 * Element.unmouseout
2423 * Removes event handler for mouseout for the element.
2425 - handler (function) handler for the event
2433 * Adds event handler for mouseover for the element.
2435 - handler (function) handler for the event
2439 * Element.unmouseover
2442 * Removes event handler for mouseover for the element.
2444 - handler (function) handler for the event
2452 * Adds event handler for mouseup for the element.
2454 - handler (function) handler for the event
2461 * Removes event handler for mouseup for the element.
2463 - handler (function) handler for the event
2468 * Element.touchstart
2471 * Adds event handler for touchstart for the element.
2473 - handler (function) handler for the event
2477 * Element.untouchstart
2480 * Removes event handler for touchstart for the element.
2482 - handler (function) handler for the event
2490 * Adds event handler for touchmove for the element.
2492 - handler (function) handler for the event
2496 * Element.untouchmove
2499 * Removes event handler for touchmove for the element.
2501 - handler (function) handler for the event
2509 * Adds event handler for touchend for the element.
2511 - handler (function) handler for the event
2515 * Element.untouchend
2518 * Removes event handler for touchend for the element.
2520 - handler (function) handler for the event
2525 * Element.touchcancel
2528 * Adds event handler for touchcancel for the element.
2530 - handler (function) handler for the event
2534 * Element.untouchcancel
2537 * Removes event handler for touchcancel for the element.
2539 - handler (function) handler for the event
2542 for (var i = events.length; i--;) {
2543 (function (eventName) {
2544 R[eventName] = elproto[eventName] = function (fn, scope) {
2545 if (R.is(fn, "function")) {
2546 this.events = this.events || [];
2547 this.events.push({name: eventName, f: fn, unbind: addEvent(this.shape || this.node || g.doc, eventName, fn, scope || this)});
2551 R["un" + eventName] = elproto["un" + eventName] = function (fn) {
2552 var events = this.events,
2554 while (l--) if (events[l].name == eventName && events[l].f == fn) {
2556 events.splice(l, 1);
2557 !events.length && delete this.events;
2569 * Adds or retrieves given value asociated with given key.
2571 * See also @Element.removeData
2573 - key (string) key to store data
2574 - value (any) #optional value to store
2576 * or, if value is not specified:
2579 | for (var i = 0, i < 5, i++) {
2580 | paper.circle(10 + 15 * i, 10, 10)
2581 | .attr({fill: "#000"})
2583 | .click(function () {
2584 | alert(this.data("i"));
2588 elproto.data = function (key, value) {
2589 var data = eldata[this.id] = eldata[this.id] || {};
2590 if (arguments.length == 1) {
2591 if (R.is(key, "object")) {
2592 for (var i in key) if (key[has](i)) {
2593 this.data(i, key[i]);
2597 eve("data.get." + this.id, this, data[key], key);
2601 eve("data.set." + this.id, this, value, key);
2605 * Element.removeData
2608 * Removes value associated with an element by given key.
2609 * If key is not provided, removes all the data of the element.
2611 - key (string) #optional key
2614 elproto.removeData = function (key) {
2616 eldata[this.id] = {};
2618 eldata[this.id] && delete eldata[this.id][key];
2626 * Adds event handlers for hover for the element.
2628 - f_in (function) handler for hover in
2629 - f_out (function) handler for hover out
2630 - icontext (object) #optional context for hover in handler
2631 - ocontext (object) #optional context for hover out handler
2634 elproto.hover = function (f_in, f_out, scope_in, scope_out) {
2635 return this.mouseover(f_in, scope_in).mouseout(f_out, scope_out || scope_in);
2641 * Removes event handlers for hover for the element.
2643 - f_in (function) handler for hover in
2644 - f_out (function) handler for hover out
2647 elproto.unhover = function (f_in, f_out) {
2648 return this.unmouseover(f_in).unmouseout(f_out);
2654 * Adds event handlers for drag of the element.
2656 - onmove (function) handler for moving
2657 - onstart (function) handler for drag start
2658 - onend (function) handler for drag end
2659 - mcontext (object) #optional context for moving handler
2660 - scontext (object) #optional context for drag start handler
2661 - econtext (object) #optional context for drag end handler
2662 * Additionaly following `drag` events will be triggered: `drag.start.<id>` on start,
2663 * `drag.end.<id>` on end and `drag.move.<id>` on every move. When element will be dragged over another element
2664 * `drag.over.<id>` will be fired as well.
2666 * Start event and start handler will be called in specified context or in context of the element with following parameters:
2667 o x (number) x position of the mouse
2668 o y (number) y position of the mouse
2669 o event (object) DOM event object
2670 * Move event and move handler will be called in specified context or in context of the element with following parameters:
2671 o dx (number) shift by x from the start point
2672 o dy (number) shift by y from the start point
2673 o x (number) x position of the mouse
2674 o y (number) y position of the mouse
2675 o event (object) DOM event object
2676 * End event and end handler will be called in specified context or in context of the element with following parameters:
2677 o event (object) DOM event object
2680 elproto.drag = function (onmove, onstart, onend, move_scope, start_scope, end_scope) {
2682 (e.originalEvent || e).preventDefault();
2683 var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
2684 scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft;
2685 this._drag.x = e.clientX + scrollX;
2686 this._drag.y = e.clientY + scrollY;
2687 this._drag.id = e.identifier;
2688 !drag.length && R.mousemove(dragMove).mouseup(dragUp);
2689 drag.push({el: this, move_scope: move_scope, start_scope: start_scope, end_scope: end_scope});
2690 onstart && eve.on("drag.start." + this.id, onstart);
2691 onmove && eve.on("drag.move." + this.id, onmove);
2692 onend && eve.on("drag.end." + this.id, onend);
2693 eve("drag.start." + this.id, start_scope || move_scope || this, e.clientX + scrollX, e.clientY + scrollY, e);
2696 this.mousedown(start);
2700 * Element.onDragOver
2703 * Shortcut for assigning event handler for `drag.over.<id>` event, where id is id of the element (see @Element.id).
2705 - f (function) handler for event, first argument would be the element you are dragging over
2707 elproto.onDragOver = function (f) {
2708 f ? eve.on("drag.over." + this.id, f) : eve.unbind("drag.over." + this.id);
2714 * Removes all drag event handlers from given element.
2716 elproto.undrag = function () {
2717 var i = drag.length;
2718 while (i--) if (drag[i].el == this) {
2719 R.unmousedown(drag[i].start);
2720 drag.splice(i++, 1);
2721 eve.unbind("drag.*." + this.id);
2723 !drag.length && R.unmousemove(dragMove).unmouseup(dragUp);
2733 - x (number) x coordinate of the centre
2734 - y (number) y coordinate of the centre
2736 = (object) Raphaël element object with type “circle”
2739 | var c = paper.circle(50, 50, 40);
2741 paperproto.circle = function (x, y, r) {
2742 var out = R._engine.circle(this, x || 0, y || 0, r || 0);
2743 this.__set__ && this.__set__.push(out);
2750 * Draws a rectangle.
2754 - x (number) x coordinate of the top left corner
2755 - y (number) y coordinate of the top left corner
2756 - width (number) width
2757 - height (number) height
2758 - r (number) #optional radius for rounded corners, default is 0
2759 = (object) Raphaël element object with type “rect”
2762 | // regular rectangle
2763 | var c = paper.rect(10, 10, 50, 50);
2764 | // rectangle with rounded corners
2765 | var c = paper.rect(40, 40, 50, 50, 10);
2767 paperproto.rect = function (x, y, w, h, r) {
2768 var out = R._engine.rect(this, x || 0, y || 0, w || 0, h || 0, r || 0);
2769 this.__set__ && this.__set__.push(out);
2780 - x (number) x coordinate of the centre
2781 - y (number) y coordinate of the centre
2782 - rx (number) horizontal radius
2783 - ry (number) vertical radius
2784 = (object) Raphaël element object with type “ellipse”
2787 | var c = paper.ellipse(50, 50, 40, 20);
2789 paperproto.ellipse = function (x, y, rx, ry) {
2790 var out = R._engine.ellipse(this, x || 0, y || 0, rx || 0, ry || 0);
2791 this.__set__ && this.__set__.push(out);
2798 * Creates a path element by given path data string.
2800 - pathString (string) #optional path string in SVG format.
2801 * Path string consists of one-letter commands, followed by comma seprarated arguments in numercal form. Example:
2803 * 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.
2805 # <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>
2806 # <table><thead><tr><th>Command</th><th>Name</th><th>Parameters</th></tr></thead><tbody>
2807 # <tr><td>M</td><td>moveto</td><td>(x y)+</td></tr>
2808 # <tr><td>Z</td><td>closepath</td><td>(none)</td></tr>
2809 # <tr><td>L</td><td>lineto</td><td>(x y)+</td></tr>
2810 # <tr><td>H</td><td>horizontal lineto</td><td>x+</td></tr>
2811 # <tr><td>V</td><td>vertical lineto</td><td>y+</td></tr>
2812 # <tr><td>C</td><td>curveto</td><td>(x1 y1 x2 y2 x y)+</td></tr>
2813 # <tr><td>S</td><td>smooth curveto</td><td>(x2 y2 x y)+</td></tr>
2814 # <tr><td>Q</td><td>quadratic Bézier curveto</td><td>(x1 y1 x y)+</td></tr>
2815 # <tr><td>T</td><td>smooth quadratic Bézier curveto</td><td>(x y)+</td></tr>
2816 # <tr><td>A</td><td>elliptical arc</td><td>(rx ry x-axis-rotation large-arc-flag sweep-flag x y)+</td></tr>
2817 # <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>
2818 * * “Catmull-Rom curveto” is a not standard SVG command and added in 2.0 to make life easier.
2820 | var c = paper.path("M10 10L90 90");
2821 | // draw a diagonal line:
2822 | // move to 10,10, line to 90,90
2824 paperproto.path = function (pathString) {
2825 pathString && !R.is(pathString, string) && !R.is(pathString[0], array) && (pathString += E);
2826 var out = R._engine.path(R.format[apply](R, arguments), this);
2827 this.__set__ && this.__set__.push(out);
2834 * Embeds an image into the surface.
2838 - src (string) URI of the source image
2839 - x (number) x coordinate position
2840 - y (number) y coordinate position
2841 - width (number) width of the image
2842 - height (number) height of the image
2843 = (object) Raphaël element object with type “image”
2846 | var c = paper.image("apple.png", 10, 10, 80, 80);
2848 paperproto.image = function (src, x, y, w, h) {
2849 var out = R._engine.image(this, src || "about:blank", x || 0, y || 0, w || 0, h || 0);
2850 this.__set__ && this.__set__.push(out);
2857 * Draws a text string. If you need line breaks, put “\n” in the string.
2861 - x (number) x coordinate position
2862 - y (number) y coordinate position
2863 - text (string) The text string to draw
2864 = (object) Raphaël element object with type “text”
2867 | var t = paper.text(50, 50, "Raphaël\nkicks\nbutt!");
2869 paperproto.text = function (x, y, text) {
2870 var out = R._engine.text(this, x || 0, y || 0, Str(text));
2871 this.__set__ && this.__set__.push(out);
2878 * Creates array-like object to keep and operate several elements at once.
2879 * Warning: it doesn’t create any elements for itself in the page, it just groups existing elements.
2880 * Sets act as pseudo elements — all methods available to an element can be used on a set.
2881 = (object) array-like object that represents set of elements
2884 | var st = paper.set();
2886 | paper.circle(10, 10, 5),
2887 | paper.circle(30, 10, 5)
2889 | st.attr({fill: "red"}); // changes the fill of both circles
2891 paperproto.set = function (itemsArray) {
2892 !R.is(itemsArray, "array") && (itemsArray = Array.prototype.splice.call(arguments, 0, arguments.length));
2893 var out = new Set(itemsArray);
2894 this.__set__ && this.__set__.push(out);
2901 * Creates @Paper.set. All elements that will be created after calling this method and before calling
2902 * @Paper.setFinish will be added to the set.
2906 | paper.circle(10, 10, 5),
2907 | paper.circle(30, 10, 5)
2908 | var st = paper.setFinish();
2909 | st.attr({fill: "red"}); // changes the fill of both circles
2911 paperproto.setStart = function (set) {
2912 this.__set__ = set || this.set();
2918 * See @Paper.setStart. This method finishes catching and returns resulting set.
2922 paperproto.setFinish = function (set) {
2923 var out = this.__set__;
2924 delete this.__set__;
2931 * If you need to change dimensions of the canvas call this method
2935 - width (number) new width of the canvas
2936 - height (number) new height of the canvas
2938 | var st = paper.set();
2940 | paper.circle(10, 10, 5),
2941 | paper.circle(30, 10, 5)
2943 | st.attr({fill: "red"});
2945 paperproto.setSize = function (width, height) {
2946 return R._engine.setSize.call(this, width, height);
2952 * Sets the view box of the paper. Practically it gives you ability to zoom and pan whole paper surface by
2953 * specifying new boundaries.
2957 - x (number) new x position, default is `0`
2958 - y (number) new y position, default is `0`
2959 - w (number) new width of the canvas
2960 - h (number) new height of the canvas
2961 - fit (boolean) `true` if you want graphics to fit into new boundary box
2963 paperproto.setViewBox = function (x, y, w, h, fit) {
2964 return R._engine.setViewBox.call(this, x, y, w, h, fit);
2970 * Points to the topmost element on the paper
2976 * Points to the bottom element on the paper
2978 paperproto.top = paperproto.bottom = null;
2983 * Points to the @Raphael object/function
2985 paperproto.raphael = R;
2986 var getOffset = function (elem) {
2987 var box = elem.getBoundingClientRect(),
2988 doc = elem.ownerDocument,
2990 docElem = doc.documentElement,
2991 clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0,
2992 top = box.top + (g.win.pageYOffset || docElem.scrollTop || body.scrollTop ) - clientTop,
2993 left = box.left + (g.win.pageXOffset || docElem.scrollLeft || body.scrollLeft) - clientLeft;
3000 * Paper.getElementByPoint
3003 * Returns you topmost element under given point.
3005 = (object) Raphaël element object
3008 - x (number) x coordinate from the top left corner of the window
3009 - y (number) y coordinate from the top left corner of the window
3011 | paper.getElementByPoint(mouseX, mouseY).attr({stroke: "#f00"});
3013 paperproto.getElementByPoint = function (x, y) {
3016 target = g.doc.elementFromPoint(x, y);
3017 if (g.win.opera && target.tagName == "svg") {
3018 var so = getOffset(svg),
3019 sr = svg.createSVGRect();
3022 sr.width = sr.height = 1;
3023 var hits = svg.getIntersectionList(sr, null);
3025 target = hits[hits.length - 1];
3031 while (target.parentNode && target != svg.parentNode && !target.raphael) {
3032 target = target.parentNode;
3034 target == paper.canvas.parentNode && (target = svg);
3035 target = target && target.raphael ? paper.getById(target.raphaelid) : null;
3042 * Returns you element by its internal ID.
3047 = (object) Raphaël element object
3049 paperproto.getById = function (id) {
3050 var bot = this.bottom;
3063 * Executes given function for each element on the paper
3065 * If callback function returns `false` it will stop loop running.
3069 - callback (function) function to run
3070 - thisArg (object) context object for the callback
3071 = (object) Paper object
3073 paperproto.forEach = function (callback, thisArg) {
3074 var bot = this.bottom;
3076 if (callback.call(thisArg, bot) === false) {
3084 return this.x + S + this.y;
3086 function x_y_w_h() {
3087 return this.x + S + this.y + S + this.width + " \xd7 " + this.height;
3093 * Return bounding box for a given element
3097 - isWithoutTransform (boolean) flag, `true` if you want to have bounding box before transformations. Default is `false`.
3098 = (object) Bounding box object:
3100 o x: (number) top left corner x
3101 o y: (number) top left corner y
3102 o width: (number) width
3103 o height: (number) height
3106 elproto.getBBox = function (isWithoutTransform) {
3111 if (isWithoutTransform) {
3112 if (_.dirty || !_.bboxwt) {
3113 this.realPath = getPath[this.type](this);
3114 _.bboxwt = pathDimensions(this.realPath);
3115 _.bboxwt.toString = x_y_w_h;
3120 if (_.dirty || _.dirtyT || !_.bbox) {
3121 if (_.dirty || !this.realPath) {
3123 this.realPath = getPath[this.type](this);
3125 _.bbox = pathDimensions(mapPath(this.realPath, this.matrix));
3126 _.bbox.toString = x_y_w_h;
3127 _.dirty = _.dirtyT = 0;
3135 = (object) clone of a given element
3138 elproto.clone = function () {
3142 var out = this.paper[this.type]().attr(this.attr());
3143 this.__set__ && this.__set__.push(out);
3150 * Return set of elements that create glow-like effect around given element. See @Paper.set.
3152 * Note: Glow is not connected to the element. If you change element attributes it won’t adjust itself.
3156 - glow (object) #optional parameters object with all properties optional:
3158 o width (number) size of the glow, default is `10`
3159 o fill (boolean) will it be filled, default is `false`
3160 o opacity (number) opacity, default is `0.5`
3161 o offsetx (number) horizontal offset, default is `0`
3162 o offsety (number) vertical offset, default is `0`
3163 o color (string) glow colour, default is `black`
3165 = (object) @Paper.set of elements that represents glow
3167 elproto.glow = function (glow) {
3168 if (this.type == "text") {
3173 width: (glow.width || 10) + (+this.attr("stroke-width") || 1),
3174 fill: glow.fill || false,
3175 opacity: glow.opacity || .5,
3176 offsetx: glow.offsetx || 0,
3177 offsety: glow.offsety || 0,
3178 color: glow.color || "#000"
3183 path = this.realPath || getPath[this.type](this);
3184 path = this.matrix ? mapPath(path, this.matrix) : path;
3185 for (var i = 1; i < c + 1; i++) {
3186 out.push(r.path(path).attr({
3188 fill: s.fill ? s.color : "none",
3189 "stroke-linejoin": "round",
3190 "stroke-linecap": "round",
3191 "stroke-width": +(s.width / c * i).toFixed(3),
3192 opacity: +(s.opacity / c).toFixed(3)
3195 return out.insertBefore(this).translate(s.offsetx, s.offsety);
3197 var curveslengths = {},
3198 getPointAtSegmentLength = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length) {
3201 name = [p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y].join(),
3202 cache = curveslengths[name],
3204 !cache && (curveslengths[name] = cache = {data: []});
3205 cache.timer && clearTimeout(cache.timer);
3206 cache.timer = setTimeout(function () {delete curveslengths[name];}, 2e3);
3207 if (length != null && !cache.precision) {
3208 var total = getPointAtSegmentLength(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y);
3209 cache.precision = ~~total * 10;
3212 precision = cache.precision || precision;
3213 for (var i = 0; i < precision + 1; i++) {
3214 if (cache.data[i * precision]) {
3215 dot = cache.data[i * precision];
3217 dot = R.findDotsAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, i / precision);
3218 cache.data[i * precision] = dot;
3220 i && (len += pow(pow(old.x - dot.x, 2) + pow(old.y - dot.y, 2), .5));
3221 if (length != null && len >= length) {
3226 if (length == null) {
3230 getLengthFactory = function (istotal, subpath) {
3231 return function (path, length, onlystart) {
3232 path = path2curve(path);
3233 var x, y, p, l, sp = "", subpaths = {}, point,
3235 for (var i = 0, ii = path.length; i < ii; i++) {
3241 l = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6]);
3242 if (len + l > length) {
3243 if (subpath && !subpaths.start) {
3244 point = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6], length - len);
3245 sp += ["C" + point.start.x, point.start.y, point.m.x, point.m.y, point.x, point.y];
3246 if (onlystart) {return sp;}
3247 subpaths.start = sp;
3248 sp = ["M" + point.x, point.y + "C" + point.n.x, point.n.y, point.end.x, point.end.y, p[5], p[6]].join();
3254 if (!istotal && !subpath) {
3255 point = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6], length - len);
3256 return {x: point.x, y: point.y, alpha: point.alpha};
3263 sp += p.shift() + p;
3266 point = istotal ? len : subpath ? subpaths : R.findDotsAtSegment(x, y, p[0], p[1], p[2], p[3], p[4], p[5], 1);
3267 point.alpha && (point = {x: point.x, y: point.y, alpha: point.alpha});
3271 var getTotalLength = getLengthFactory(1),
3272 getPointAtLength = getLengthFactory(),
3273 getSubpathsAtLength = getLengthFactory(0, 1);
3275 * Raphael.getTotalLength
3278 * Returns length of the given path in pixels.
3282 - path (string) SVG path string.
3286 R.getTotalLength = getTotalLength;
3288 * Raphael.getPointAtLength
3291 * Return coordinates of the point located at the given length on the given path.
3295 - path (string) SVG path string
3298 = (object) representation of the point:
3300 o x: (number) x coordinate
3301 o y: (number) y coordinate
3302 o alpha: (number) angle of derivative
3305 R.getPointAtLength = getPointAtLength;
3307 * Raphael.getSubpath
3310 * Return subpath of a given path from given length to given length.
3314 - path (string) SVG path string
3315 - from (number) position of the start of the segment
3316 - to (number) position of the end of the segment
3318 = (string) pathstring for the segment
3320 R.getSubpath = function (path, from, to) {
3321 if (this.getTotalLength(path) - to < 1e-6) {
3322 return getSubpathsAtLength(path, from).end;
3324 var a = getSubpathsAtLength(path, to, 1);
3325 return from ? getSubpathsAtLength(a, from).end : a;
3328 * Element.getTotalLength
3331 * Returns length of the path in pixels. Only works for element of “path” type.
3334 elproto.getTotalLength = function () {
3335 if (this.type != "path") {return;}
3336 if (this.node.getTotalLength) {
3337 return this.node.getTotalLength();
3339 return getTotalLength(this.attrs.path);
3342 * Element.getPointAtLength
3345 * Return coordinates of the point located at the given length on the given path. Only works for element of “path” type.
3351 = (object) representation of the point:
3353 o x: (number) x coordinate
3354 o y: (number) y coordinate
3355 o alpha: (number) angle of derivative
3358 elproto.getPointAtLength = function (length) {
3359 if (this.type != "path") {return;}
3360 return getPointAtLength(this.attrs.path, length);
3363 * Element.getSubpath
3366 * Return subpath of a given element from given length to given length. Only works for element of “path” type.
3370 - from (number) position of the start of the segment
3371 - to (number) position of the end of the segment
3373 = (string) pathstring for the segment
3375 elproto.getSubpath = function (from, to) {
3376 if (this.type != "path") {return;}
3377 return R.getSubpath(this.attrs.path, from, to);
3380 * Raphael.easing_formulas
3383 * Object that contains easing formulas for animation. You could extend it with your own. By default it has following list of easing:
3386 # <li>“<” or “easeIn” or “ease-in”</li>
3387 # <li>“>” or “easeOut” or “ease-out”</li>
3388 # <li>“<>” or “easeInOut” or “ease-in-out”</li>
3389 # <li>“backIn” or “back-in”</li>
3390 # <li>“backOut” or “back-out”</li>
3391 # <li>“elastic”</li>
3394 # <p>See also <a href="http://raphaeljs.com/easing.html">Easing demo</a>.</p>
3396 var ef = R.easing_formulas = {
3397 linear: function (n) {
3406 "<>": function (n) {
3407 var q = .48 - n / 1.04,
3408 Q = math.sqrt(.1734 + q * q),
3410 X = pow(abs(x), 1 / 3) * (x < 0 ? -1 : 1),
3412 Y = pow(abs(y), 1 / 3) * (y < 0 ? -1 : 1),
3414 return (1 - t) * 3 * t * t + t * t * t;
3416 backIn: function (n) {
3418 return n * n * ((s + 1) * n - s);
3420 backOut: function (n) {
3423 return n * n * ((s + 1) * n + s) + 1;
3425 elastic: function (n) {
3429 return pow(2, -10 * n) * math.sin((n - .075) * (2 * PI) / .3) + 1;
3431 bounce: function (n) {
3440 l = s * n * n + .75;
3442 if (n < (2.5 / p)) {
3444 l = s * n * n + .9375;
3447 l = s * n * n + .984375;
3454 ef.easeIn = ef["ease-in"] = ef["<"];
3455 ef.easeOut = ef["ease-out"] = ef[">"];
3456 ef.easeInOut = ef["ease-in-out"] = ef["<>"];
3457 ef["back-in"] = ef.backIn;
3458 ef["back-out"] = ef.backOut;
3460 var animationElements = [],
3461 requestAnimFrame = window.requestAnimationFrame ||
3462 window.webkitRequestAnimationFrame ||
3463 window.mozRequestAnimationFrame ||
3464 window.oRequestAnimationFrame ||
3465 window.msRequestAnimationFrame ||
3466 function (callback) {
3467 setTimeout(callback, 16);
3469 animation = function () {
3470 var Now = +new Date,
3472 for (; l < animationElements.length; l++) {
3473 var e = animationElements[l];
3474 if (e.el.removed || e.paused) {
3477 var time = Now - e.start,
3490 time = (e.initstatus * e.anim.top - e.prev) / (e.percent - e.prev) * ms;
3491 e.status = e.initstatus;
3492 delete e.initstatus;
3493 e.stop && animationElements.splice(l--, 1);
3495 e.status = (e.prev + (e.percent - e.prev) * (time / ms)) / e.anim.top;
3501 var pos = easing(time / ms);
3502 for (var attr in from) if (from[has](attr)) {
3503 switch (availableAnimAttrs[attr]) {
3505 now = +from[attr] + pos * ms * diff[attr];
3509 upto255(round(from[attr].r + pos * ms * diff[attr].r)),
3510 upto255(round(from[attr].g + pos * ms * diff[attr].g)),
3511 upto255(round(from[attr].b + pos * ms * diff[attr].b))
3516 for (var i = 0, ii = from[attr].length; i < ii; i++) {
3517 now[i] = [from[attr][i][0]];
3518 for (var j = 1, jj = from[attr][i].length; j < jj; j++) {
3519 now[i][j] = +from[attr][i][j] + pos * ms * diff[attr][i][j];
3521 now[i] = now[i].join(S);
3526 if (diff[attr].real) {
3528 for (i = 0, ii = from[attr].length; i < ii; i++) {
3529 now[i] = [from[attr][i][0]];
3530 for (j = 1, jj = from[attr][i].length; j < jj; j++) {
3531 now[i][j] = from[attr][i][j] + pos * ms * diff[attr][i][j];
3535 var get = function (i) {
3536 return +from[attr][i] + pos * ms * diff[attr][i];
3538 // now = [["r", get(2), 0, 0], ["t", get(3), get(4)], ["s", get(0), get(1), 0, 0]];
3539 now = [["m", get(0), get(1), get(2), get(3), get(4), get(5)]];
3543 if (attr == "clip-rect") {
3547 now[i] = +from[attr][i] + pos * ms * diff[attr][i];
3552 var from2 = [][concat](from[attr]);
3554 i = that.paper.customAttributes[attr].length;
3556 now[i] = +from2[i] + pos * ms * diff[attr][i];
3563 (function (id, that, anim) {
3564 setTimeout(function () {
3565 eve("anim.frame." + id, that, anim);
3567 })(that.id, that, e.anim);
3569 (function(f, el, a) {
3570 setTimeout(function() {
3571 eve("anim.frame." + el.id, el, a);
3572 eve("anim.finish." + el.id, el, a);
3573 R.is(f, "function") && f.call(el);
3575 })(e.callback, that, e.anim);
3577 animationElements.splice(l--, 1);
3578 if (e.repeat > 1 && !e.next) {
3579 for (key in to) if (to[has](key)) {
3580 init[key] = e.totalOrigin[key];
3583 runAnimation(e.anim, e.el, e.anim.percents[0], null, e.totalOrigin, e.repeat - 1);
3585 if (e.next && !e.stop) {
3586 runAnimation(e.anim, e.el, e.next, null, e.totalOrigin, e.repeat);
3590 R.svg && that && that.paper && that.paper.safari();
3591 animationElements.length && requestAnimFrame(animation);
3593 upto255 = function (color) {
3594 return color > 255 ? 255 : color < 0 ? 0 : color;
3597 * Element.animateWith
3600 * Acts similar to @Element.animate, but ensure that given animation runs in sync with another given element.
3604 - element (object) element to sync with
3605 - anim (object) animation to sync with
3606 - params (object) #optional final attributes for the element, see also @Element.attr
3607 - ms (number) #optional number of milliseconds for animation to run
3608 - easing (string) #optional easing type. Accept on of @Raphael.easing_formulas or CSS format: `cubic‐bezier(XX, XX, XX, XX)`
3609 - callback (function) #optional callback function. Will be called at the end of animation.
3611 - element (object) element to sync with
3612 - anim (object) animation to sync with
3613 - animation (object) #optional animation object, see @Raphael.animation
3615 = (object) original element
3617 elproto.animateWith = function (element, anim, params, ms, easing, callback) {
3618 var a = params ? R.animation(params, ms, easing, callback) : anim;
3619 status = element.status(anim);
3620 return this.animate(a).status(a, status * anim.ms / a.ms);
3622 function CubicBezierAtTime(t, p1x, p1y, p2x, p2y, duration) {
3624 bx = 3 * (p2x - p1x) - cx,
3627 by = 3 * (p2y - p1y) - cy,
3629 function sampleCurveX(t) {
3630 return ((ax * t + bx) * t + cx) * t;
3632 function solve(x, epsilon) {
3633 var t = solveCurveX(x, epsilon);
3634 return ((ay * t + by) * t + cy) * t;
3636 function solveCurveX(x, epsilon) {
3637 var t0, t1, t2, x2, d2, i;
3638 for(t2 = x, i = 0; i < 8; i++) {
3639 x2 = sampleCurveX(t2) - x;
3640 if (abs(x2) < epsilon) {
3643 d2 = (3 * ax * t2 + 2 * bx) * t2 + cx;
3644 if (abs(d2) < 1e-6) {
3659 x2 = sampleCurveX(t2);
3660 if (abs(x2 - x) < epsilon) {
3668 t2 = (t1 - t0) / 2 + t0;
3672 return solve(t, 1 / (200 * duration));
3674 elproto.onAnimation = function (f) {
3675 f ? eve.on("anim.frame." + this.id, f) : eve.unbind("anim.frame." + this.id);
3678 function Animation(anim, ms) {
3684 for (var attr in anim) if (anim[has](attr)) {
3685 newAnim[toFloat(attr)] = anim[attr];
3686 percents.push(toFloat(attr));
3688 percents.sort(sortByNumber);
3690 this.anim = newAnim;
3691 this.top = percents[percents.length - 1];
3692 this.percents = percents;
3698 * Creates a copy of existing animation object with given delay.
3702 - delay (number) number of ms to pass between animation start and actual animation
3704 = (object) new altered Animation object
3705 | var anim = Raphael.animation({cx: 10, cy: 20}, 2e3);
3706 | circle1.animate(anim); // run the given animation immediately
3707 | circle2.animate(anim.delay(500)); // run the given animation after 500 ms
3709 Animation.prototype.delay = function (delay) {
3710 var a = new Animation(this.anim, this.ms);
3711 a.times = this.times;
3712 a.del = +delay || 0;
3719 * Creates a copy of existing animation object with given repetition.
3723 - repeat (number) number iterations of animation. For infinite animation pass `Infinity`
3725 = (object) new altered Animation object
3727 Animation.prototype.repeat = function (times) {
3728 var a = new Animation(this.anim, this.ms);
3730 a.times = math.floor(mmax(times, 0)) || 1;
3733 function runAnimation(anim, element, percent, status, totalOrigin, times) {
3734 percent = toFloat(percent);
3747 for (i = 0, ii = animationElements.length; i < ii; i++) {
3748 var e = animationElements[i];
3749 if (e.el.id == element.id && e.anim == anim) {
3750 if (e.percent != percent) {
3751 animationElements.splice(i, 1);
3756 element.attr(e.totalOrigin);
3761 status = +to; // NaN
3763 for (var i = 0, ii = anim.percents.length; i < ii; i++) {
3764 if (anim.percents[i] == percent || anim.percents[i] > status * anim.top) {
3765 percent = anim.percents[i];
3766 prev = anim.percents[i - 1] || 0;
3767 ms = ms / anim.top * (percent - prev);
3768 next = anim.percents[i + 1];
3769 params = anim.anim[percent];
3771 } else if (status) {
3772 element.attr(anim.anim[anim.percents[i]]);
3779 for (attr in params) if (params[has](attr)) {
3780 if (availableAnimAttrs[has](attr) || element.paper.customAttributes[has](attr)) {
3781 from[attr] = element.attr(attr);
3782 (from[attr] == null) && (from[attr] = availableAttrs[attr]);
3783 to[attr] = params[attr];
3784 switch (availableAnimAttrs[attr]) {
3786 diff[attr] = (to[attr] - from[attr]) / ms;
3789 from[attr] = R.getRGB(from[attr]);
3790 var toColour = R.getRGB(to[attr]);
3792 r: (toColour.r - from[attr].r) / ms,
3793 g: (toColour.g - from[attr].g) / ms,
3794 b: (toColour.b - from[attr].b) / ms
3798 var pathes = path2curve(from[attr], to[attr]),
3800 from[attr] = pathes[0];
3802 for (i = 0, ii = from[attr].length; i < ii; i++) {
3803 diff[attr][i] = [0];
3804 for (var j = 1, jj = from[attr][i].length; j < jj; j++) {
3805 diff[attr][i][j] = (toPath[i][j] - from[attr][i][j]) / ms;
3811 eq = equaliseTransform(_[attr], to[attr]);
3813 from[attr] = eq.from;
3816 diff[attr].real = true;
3817 for (i = 0, ii = from[attr].length; i < ii; i++) {
3818 diff[attr][i] = [from[attr][i][0]];
3819 for (j = 1, jj = from[attr][i].length; j < jj; j++) {
3820 diff[attr][i][j] = (to[attr][i][j] - from[attr][i][j]) / ms;
3824 var m = (element.matrix || new Matrix),
3826 _: {transform: _.transform},
3827 getBBox: function () {
3828 return element.getBBox(1);
3839 extractTransform(to2, to[attr]);
3840 to[attr] = to2._.transform;
3842 (to2.matrix.a - m.a) / ms,
3843 (to2.matrix.b - m.b) / ms,
3844 (to2.matrix.c - m.c) / ms,
3845 (to2.matrix.d - m.d) / ms,
3846 (to2.matrix.e - m.e) / ms,
3847 (to2.matrix.e - m.f) / ms
3849 // from[attr] = [_.sx, _.sy, _.deg, _.dx, _.dy];
3850 // var to2 = {_:{}, getBBox: function () { return element.getBBox(); }};
3851 // extractTransform(to2, to[attr]);
3853 // (to2._.sx - _.sx) / ms,
3854 // (to2._.sy - _.sy) / ms,
3855 // (to2._.deg - _.deg) / ms,
3856 // (to2._.dx - _.dx) / ms,
3857 // (to2._.dy - _.dy) / ms
3862 var values = Str(params[attr])[split](separator),
3863 from2 = Str(from[attr])[split](separator);
3864 if (attr == "clip-rect") {
3869 diff[attr][i] = (values[i] - from[attr][i]) / ms;
3875 values = [][concat](params[attr]);
3876 from2 = [][concat](from[attr]);
3878 i = element.paper.customAttributes[attr].length;
3880 diff[attr][i] = ((values[i] || 0) - (from2[i] || 0)) / ms;
3886 var easing = params.easing,
3887 easyeasy = R.easing_formulas[easing];
3889 easyeasy = Str(easing).match(bezierrg);
3890 if (easyeasy && easyeasy.length == 5) {
3891 var curve = easyeasy;
3892 easyeasy = function (t) {
3893 return CubicBezierAtTime(t, +curve[1], +curve[2], +curve[3], +curve[4], ms);
3899 timestamp = params.start || anim.start || +new Date;
3903 timestamp: timestamp,
3904 start: timestamp + (anim.del || 0),
3906 initstatus: status || 0,
3914 callback: params.callback,
3917 repeat: times || anim.times,
3918 origin: element.attr(),
3919 totalOrigin: totalOrigin
3921 animationElements.push(e);
3922 if (status && !isInAnim && !isInAnimSet) {
3924 e.start = new Date - ms * status;
3925 if (animationElements.length == 1) {
3930 e.start = new Date - e.ms * status;
3932 animationElements.length == 1 && requestAnimFrame(animation);
3934 isInAnim.initstatus = status;
3935 isInAnim.start = new Date - isInAnim.ms * status;
3937 eve("anim.start." + element.id, element, anim);
3943 * Creates an animation object that can be passed to the @Element.animate or @Element.animateWith methods.
3944 * See also @Animation.delay and @Animation.repeat methods.
3948 - params (object) final attributes for the element, see also @Element.attr
3949 - ms (number) number of milliseconds for animation to run
3950 - easing (string) #optional easing type. Accept one of @Raphael.easing_formulas or CSS format: `cubic‐bezier(XX, XX, XX, XX)`
3951 - callback (function) #optional callback function. Will be called at the end of animation.
3953 = (object) @Animation
3955 R.animation = function (params, ms, easing, callback) {
3956 if (params instanceof Animation) {
3959 if (R.is(easing, "function") || !easing) {
3960 callback = callback || easing || null;
3963 params = Object(params);
3968 for (attr in params) if (params[has](attr) && toFloat(attr) != attr && toFloat(attr) + "%" != attr) {
3970 p[attr] = params[attr];
3973 return new Animation(params, ms);
3975 easing && (p.easing = easing);
3976 callback && (p.callback = callback);
3977 return new Animation({100: p}, ms);
3984 * Creates and starts animation for given element.
3988 - params (object) final attributes for the element, see also @Element.attr
3989 - ms (number) number of milliseconds for animation to run
3990 - easing (string) #optional easing type. Accept one of @Raphael.easing_formulas or CSS format: `cubic‐bezier(XX, XX, XX, XX)`
3991 - callback (function) #optional callback function. Will be called at the end of animation.
3993 - animation (object) animation object, see @Raphael.animation
3995 = (object) original element
3997 elproto.animate = function (params, ms, easing, callback) {
3999 if (element.removed) {
4000 callback && callback.call(element);
4003 var anim = params instanceof Animation ? params : R.animation(params, ms, easing, callback);
4004 runAnimation(anim, element, anim.percents[0], null, element.attr());
4011 * Sets the status of animation of the element in milliseconds. Similar to @Element.status method.
4015 - anim (object) animation object
4016 - value (number) number of milliseconds from the beginning of the animation
4018 = (object) original element if `value` is specified
4019 * Note, that during animation following events are triggered:
4021 * On each animation frame event `anim.frame.<id>`, on start `anim.start.<id>` and on end `anim.finish.<id>`.
4023 elproto.setTime = function (anim, value) {
4024 if (anim && value != null) {
4025 this.status(anim, mmin(value, anim.ms) / anim.ms);
4033 * Gets or sets the status of animation of the element.
4037 - anim (object) #optional animation object
4038 - 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.
4042 = (array) status if `anim` is not specified. Array of objects in format:
4044 o anim: (object) animation object
4045 o status: (number) status
4048 = (object) original element if `value` is specified
4050 elproto.status = function (anim, value) {
4055 if (value != null) {
4056 runAnimation(anim, this, -1, mmin(value, 1));
4059 len = animationElements.length;
4060 for (; i < len; i++) {
4061 e = animationElements[i];
4062 if (e.el.id == this.id && (!anim || e.anim == anim)) {
4082 * Stops animation of the element with ability to resume it later on.
4086 - anim (object) #optional animation object
4088 = (object) original element
4090 elproto.pause = function (anim) {
4091 for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) {
4092 if (eve("anim.pause." + this.id, this, animationElements[i].anim) !== false) {
4093 animationElements[i].paused = true;
4102 * Resumes animation if it was paused with @Element.pause method.
4106 - anim (object) #optional animation object
4108 = (object) original element
4110 elproto.resume = function (anim) {
4111 for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) {
4112 var e = animationElements[i];
4113 if (eve("anim.resume." + this.id, this, e.anim) !== false) {
4115 this.status(e.anim, e.status);
4124 * Stops animation of the element.
4128 - anim (object) #optional animation object
4130 = (object) original element
4132 elproto.stop = function (anim) {
4133 for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) {
4134 if (eve("anim.stop." + this.id, this, animationElements[i].anim) !== false) {
4135 animationElements.splice(i--, 1);
4140 elproto.toString = function () {
4141 return "Rapha\xebl\u2019s object";
4145 var Set = function (items) {
4150 for (var i = 0, ii = items.length; i < ii; i++) {
4151 if (items[i] && (items[i].constructor == elproto.constructor || items[i].constructor == Set)) {
4152 this[this.items.length] = this.items[this.items.length] = items[i];
4158 setproto = Set.prototype;
4163 * Adds each argument to the current set.
4164 = (object) original element
4166 setproto.push = function () {
4169 for (var i = 0, ii = arguments.length; i < ii; i++) {
4170 item = arguments[i];
4171 if (item && (item.constructor == elproto.constructor || item.constructor == Set)) {
4172 len = this.items.length;
4173 this[len] = this.items[len] = item;
4183 * Removes last element and returns it.
4186 setproto.pop = function () {
4187 this.length && delete this[this.length--];
4188 return this.items.pop();
4194 * Executes given function for each element in the set.
4196 * If function returns `false` it will stop loop running.
4200 - callback (function) function to run
4201 - thisArg (object) context object for the callback
4202 = (object) Set object
4204 setproto.forEach = function (callback, thisArg) {
4205 for (var i = 0, ii = this.items.length; i < ii; i++) {
4206 if (callback.call(thisArg, this.items[i], i) === false) {
4212 for (var method in elproto) if (elproto[has](method)) {
4213 setproto[method] = (function (methodname) {
4214 return function () {
4215 var arg = arguments;
4216 return this.forEach(function (el) {
4217 el[methodname][apply](el, arg);
4222 setproto.attr = function (name, value) {
4223 if (name && R.is(name, array) && R.is(name[0], "object")) {
4224 for (var j = 0, jj = name.length; j < jj; j++) {
4225 this.items[j].attr(name[j]);
4228 for (var i = 0, ii = this.items.length; i < ii; i++) {
4229 this.items[i].attr(name, value);
4238 * Removeds all elements from the set
4240 setproto.clear = function () {
4241 while (this.length) {
4249 * Removes given element from the set
4253 - index (number) position of the deletion
4254 - count (number) number of element to remove
4255 - insertion… (object) #optional elements to insert
4256 = (object) set elements that were deleted
4258 setproto.splice = function (index, count, insertion) {
4259 index = index < 0 ? mmax(this.length + index, 0) : index;
4260 count = mmax(0, mmin(this.length - index, count));
4265 for (i = 2; i < arguments.length; i++) {
4266 args.push(arguments[i]);
4268 for (i = 0; i < count; i++) {
4269 todel.push(this[index + i]);
4271 for (; i < this.length - index; i++) {
4272 tail.push(this[index + i]);
4274 var arglen = args.length;
4275 for (i = 0; i < arglen + tail.length; i++) {
4276 this.items[index + i] = this[index + i] = i < arglen ? args[i] : tail[i - arglen];
4278 i = this.items.length = this.length -= count - arglen;
4282 return new Set(todel);
4288 * Removes given element from the set
4292 - element (object) element to remove
4293 = (boolean) `true` if object was found & removed from the set
4295 setproto.exclude = function (el) {
4296 for (var i = 0, ii = this.length; i < ii; i++) if (this[i] == el) {
4301 setproto.animate = function (params, ms, easing, callback) {
4302 (R.is(easing, "function") || !easing) && (callback = easing || null);
4303 var len = this.items.length,
4311 callback && (collector = function () {
4312 !--len && callback.call(set);
4314 easing = R.is(easing, string) ? easing : collector;
4315 var anim = R.animation(params, ms, easing, collector);
4316 item = this.items[--i].animate(anim);
4318 this.items[i] && !this.items[i].removed && this.items[i].animateWith(item, anim);
4322 setproto.insertAfter = function (el) {
4323 var i = this.items.length;
4325 this.items[i].insertAfter(el);
4329 setproto.getBBox = function () {
4334 for (var i = this.items.length; i--;) if (!this.items[i].removed) {
4335 var box = this.items[i].getBBox();
4338 w.push(box.x + box.width);
4339 h.push(box.y + box.height);
4341 x = mmin[apply](0, x);
4342 y = mmin[apply](0, y);
4346 width: mmax[apply](0, w) - x,
4347 height: mmax[apply](0, h) - y
4350 setproto.clone = function (s) {
4352 for (var i = 0, ii = this.items.length; i < ii; i++) {
4353 s.push(this.items[i].clone());
4357 setproto.toString = function () {
4358 return "Rapha\xebl\u2018s set";
4362 * Raphael.registerFont
4365 * 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.
4366 * Returns original parameter, so it could be used with chaining.
4367 # <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>
4371 - font (object) the font to register
4372 = (object) the font you passed in
4374 | Cufon.registerFont(Raphael.registerFont({…}));
4376 R.registerFont = function (font) {
4380 this.fonts = this.fonts || {};
4386 family = font.face["font-family"];
4387 for (var prop in font.face) if (font.face[has](prop)) {
4388 fontcopy.face[prop] = font.face[prop];
4390 if (this.fonts[family]) {
4391 this.fonts[family].push(fontcopy);
4393 this.fonts[family] = [fontcopy];
4396 fontcopy.face["units-per-em"] = toInt(font.face["units-per-em"], 10);
4397 for (var glyph in font.glyphs) if (font.glyphs[has](glyph)) {
4398 var path = font.glyphs[glyph];
4399 fontcopy.glyphs[glyph] = {
4402 d: path.d && "M" + path.d.replace(/[mlcxtrv]/g, function (command) {
4403 return {l: "L", c: "C", x: "z", t: "m", r: "l", v: "c"}[command] || "M";
4407 for (var k in path.k) if (path[has](k)) {
4408 fontcopy.glyphs[glyph].k[k] = path.k[k];
4419 * 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”.
4423 - family (string) font family name or any word from it
4424 - weight (string) #optional font weight
4425 - style (string) #optional font style
4426 - stretch (string) #optional font stretch
4427 = (object) the font object
4429 | paper.print(100, 100, "Test string", paper.getFont("Times", 800), 30);
4431 paperproto.getFont = function (family, weight, style, stretch) {
4432 stretch = stretch || "normal";
4433 style = style || "normal";
4434 weight = +weight || {normal: 400, bold: 700, lighter: 300, bolder: 800}[weight] || 400;
4438 var font = R.fonts[family];
4440 var name = new RegExp("(^|\\s)" + family.replace(/[^\w\d\s+!~.:_-]/g, E) + "(\\s|$)", "i");
4441 for (var fontName in R.fonts) if (R.fonts[has](fontName)) {
4442 if (name.test(fontName)) {
4443 font = R.fonts[fontName];
4450 for (var i = 0, ii = font.length; i < ii; i++) {
4452 if (thefont.face["font-weight"] == weight && (thefont.face["font-style"] == style || !thefont.face["font-style"]) && thefont.face["font-stretch"] == stretch) {
4463 * Creates set of shapes to represent given font at given position with given size.
4464 * Result of the method is set object (see @Paper.set) which contains each letter as separate path object.
4468 - x (number) x position of the text
4469 - y (number) y position of the text
4470 - text (string) text to print
4471 - font (object) font object, see @Paper.getFont
4472 - size (number) #optional size of the font, default is `16`
4473 - origin (string) #optional could be `"baseline"` or `"middle"`, default is `"middle"`
4474 - letter_spacing (number) #optional number in range `-1..1`, default is `0`
4475 = (object) resulting set of letters
4477 | var txt = r.print(10, 50, "print", r.getFont("Museo"), 30).attr({fill: "#fff"});
4478 | // following line will paint first letter in red
4479 | txt[0].attr({fill: "#f00"});
4481 paperproto.print = function (x, y, string, font, size, origin, letter_spacing) {
4482 origin = origin || "middle"; // baseline|middle
4483 letter_spacing = mmax(mmin(letter_spacing || 0, 1), -1);
4484 var out = this.set(),
4485 letters = Str(string)[split](E),
4489 R.is(font, string) && (font = this.getFont(font));
4491 scale = (size || 16) / font.face["units-per-em"];
4492 var bb = font.face.bbox[split](separator),
4494 height = +bb[1] + (origin == "baseline" ? bb[3] - bb[1] + (+font.face.descent) : (bb[3] - bb[1]) / 2);
4495 for (var i = 0, ii = letters.length; i < ii; i++) {
4496 var prev = i && font.glyphs[letters[i - 1]] || {},
4497 curr = font.glyphs[letters[i]];
4498 shift += i ? (prev.w || font.w) + (prev.k && prev.k[letters[i]] || 0) + (font.w * letter_spacing) : 0;
4499 curr && curr.d && out.push(this.path(curr.d).attr({
4502 transform: [["t", shift * scale, 0]]
4505 out.transform(["...s", scale, scale, top, height, "t", (x - top) / scale, (y - height) / scale]);
4514 * Simple format function. Replaces construction of type “`{<number>}`” to the corresponding argument.
4518 - token (string) string to format
4519 - … (string) rest of arguments will be treated as parameters for replacement
4520 = (string) formated string
4526 | // this will draw a rectangular shape equivalent to "M10,20h40v50h-40z"
4527 | paper.path(Raphael.format("M{1},{2}h{3}v{4}h{5}z", x, y, width, height, -width));
4529 R.format = function (token, params) {
4530 var args = R.is(params, array) ? [0][concat](params) : arguments;
4531 token && R.is(token, string) && args.length - 1 && (token = token.replace(formatrg, function (str, i) {
4532 return args[++i] == null ? E : args[i];
4540 * A little bit more advanced format function than @Raphael.format. Replaces construction of type “`{<name>}`” to the corresponding argument.
4544 - token (string) string to format
4545 - json (object) object which properties will be used as a replacement
4546 = (string) formated string
4548 | // this will draw a rectangular shape equivalent to "M10,20h40v50h-40z"
4549 | paper.path(Raphael.format("M{x},{y}h{dim.width}v{dim.height}h{dim['negative width']}z", {
4555 | "negative width": -40
4559 R.fullfill = (function () {
4560 var tokenRegex = /\{([^\}]+)\}/g,
4561 objNotationRegex = /(?:(?:^|\.)(.+?)(?=\[|\.|$|\()|\[('|")(.+?)\2\])(\(\))?/g, // matches .xxxxx or ["xxxxx"] to run over object properties
4562 replacer = function (all, key, obj) {
4564 key.replace(objNotationRegex, function (all, name, quote, quotedName, isFunc) {
4565 name = name || quotedName;
4570 typeof res == "function" && isFunc && (res = res());
4573 res = (res == null || res == obj ? all : res) + "";
4576 return function (str, obj) {
4577 return String(str).replace(tokenRegex, function (all, key) {
4578 return replacer(all, key, obj);
4586 * 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.
4587 * Beware, that in this case plugins could stop working, because they are depending on global variable existance.
4589 = (object) Raphael object
4591 | (function (local_raphael) {
4592 | var paper = local_raphael(10, 10, 320, 200);
4594 | })(Raphael.ninja());
4596 R.ninja = function () {
4597 oldRaphael.was ? (g.win.Raphael = oldRaphael.is) : delete Raphael;
4602 [ property (object) ]
4604 * You can add your own method to elements and sets. It is wise to add a set method for each element method
4605 * you added, so you will be able to call the same method on sets too.
4607 * See also @Raphael.el.
4609 | Raphael.el.red = function () {
4610 | this.attr({fill: "#f00"});
4612 | Raphael.st.red = function () {
4613 | this.forEach(function () {
4618 | paper.set(paper.circle(100, 100, 20), paper.circle(110, 100, 20)).red();
4621 // Firefox <3.6 fix: http://webreflection.blogspot.com/2009/11/195-chars-to-help-lazy-loading.html
4622 (function (doc, loaded, f) {
4623 if (doc.readyState == null && doc.addEventListener){
4624 doc.addEventListener(loaded, f = function () {
4625 doc.removeEventListener(loaded, f, false);
4626 doc.readyState = "complete";
4628 doc.readyState = "loading";
4630 function isLoaded() {
4631 (/in/).test(doc.readyState) ? setTimeout(isLoaded, 9) : R.eve("DOMload");
4634 })(document, "DOMContentLoaded");
4636 oldRaphael.was ? (g.win.Raphael = R) : (Raphael = R);
4638 eve.on("DOMload", function () {