1 // ┌─────────────────────────────────────────────────────────────────────┐ \\
2 // │ Raphaël 2 - 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);
89 elements = {circle: 1, rect: 1, path: 1, ellipse: 1, text: 1, image: 1},
90 formatrg = /\{(\d+)\}/g,
92 has = "hasOwnProperty",
98 was: Object.prototype[has].call(g.win, "Raphael"),
101 Paper = function () {},
103 appendChild = "appendChild",
106 supportsTouch = "createTouch" in g.doc,
111 events = "click dblclick mousedown mousemove mouseout mouseover mouseup touchstart touchmove touchend orientationchange touchcancel gesturestart gesturechange gestureend".split(S),
113 mousedown: "touchstart",
114 mousemove: "touchmove",
117 lowerCase = Str.prototype.toLowerCase,
127 toString = "toString",
129 objectToString = Object.prototype.toString,
132 ISURL = R._ISURL = /^url\(['"]?([^\)]+?)['"]?\)$/i,
133 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,
134 isnan = {"NaN": 1, "Infinity": 1, "-Infinity": 1},
135 bezierrg = /^(?:cubic-)?bezier\(([^,]+),([^,]+),([^,]+),([^\)]+)\)/,
137 setAttribute = "setAttribute",
138 toFloat = parseFloat,
140 ms = " progid:DXImageTransform.Microsoft",
141 upperCase = Str.prototype.toUpperCase,
142 availableAttrs = R._availableAttrs = {
144 "arrow-start": "none",
146 "clip-rect": "0 0 1e9 1e9",
152 font: '10px "Arial"',
153 "font-family": '"Arial"',
155 "font-style": "normal",
159 href: "http://raphaeljs.com/",
167 "stroke-dasharray": "",
168 "stroke-linecap": "butt",
169 "stroke-linejoin": "butt",
170 "stroke-miterlimit": 0,
174 "text-anchor": "middle",
181 availableAnimAttrs = R._availableAnimAttrs = {
196 "stroke-opacity": nu,
198 transform: "transform",
203 commaSpaces = /\s*,\s*/,
204 hsrg = {hs: 1, rg: 1},
205 p2s = /,?([achlmqrstvxz]),?/gi,
206 pathCommand = /([achlmqstvz])[\s,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?\s*,?\s*)+)/ig,
207 tCommand = /([rstm])[\s,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?\s*,?\s*)+)/ig,
208 pathValues = /(-?\d*\.?\d*(?:e[\-+]?\d+)?)\s*,?\s*/ig,
209 radial_gradient = R._radial_gradient = /^r(?:\(([^,]+?)\s*,\s*([^\)]+?)\))?/,
210 sortByKey = function (a, b) {
211 return a.key - b.key;
213 sortByNumber = function (a, b) {
216 fun = function () {},
217 pipe = function (x) {
220 rectPath = R._rectPath = function (x, y, w, h, r) {
222 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"]];
224 return [["M", x, y], ["l", w, 0], ["l", 0, h], ["l", -w, 0], ["z"]];
226 ellipsePath = function (x, y, rx, ry) {
230 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"]];
232 getPath = R._getPath = {
233 path: function (el) {
234 return el.attr("path");
236 circle: function (el) {
238 return ellipsePath(a.cx, a.cy, a.r);
240 ellipse: function (el) {
242 return ellipsePath(a.cx, a.cy, a.rx, a.ry);
244 rect: function (el) {
246 return rectPath(a.x, a.y, a.width, a.height, a.r);
248 image: function (el) {
250 return rectPath(a.x, a.y, a.width, a.height);
252 text: function (el) {
253 var bbox = el._getBBox();
254 return rectPath(bbox.x, bbox.y, bbox.width, bbox.height);
257 mapPath = function (path, matrix) {
261 var x, y, i, j, pathi;
262 path = path2curve(path);
263 for (i = 0, ii = path.length; i < ii; i++) {
265 for (j = 1, jj = pathi.length; j < jj; j += 2) {
266 x = matrix.x(pathi[j], pathi[j + 1]);
267 y = matrix.y(pathi[j], pathi[j + 1]);
278 [ property (string) ]
280 * Can be “SVG”, “VML” or empty, depending on browser support.
282 R.type = (g.win.SVGAngle || g.doc.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") ? "SVG" : "VML");
283 if (R.type == "VML") {
284 var d = g.doc.createElement("div"),
286 d.innerHTML = '<v:shape adj="1"/>';
288 b.style.behavior = "url(#default#VML)";
289 if (!(b && typeof b.adj == "object")) {
296 [ property (boolean) ]
298 * `true` if browser supports SVG.
302 [ property (boolean) ]
304 * `true` if browser supports VML.
306 R.svg = !(R.vml = R.type == "VML");
310 [ property (object) ]
312 * You can add your own method to the canvas. For example if you want to draw a pie chart,
313 * you can create your own pie chart function and ship it as a Raphaël plugin. To do this
314 * you need to extend the `Raphael.fn` object. Please note that you can create your own namespaces
315 * inside the `fn` object — methods will be run in the context of canvas anyway. You should alter
316 * the `fn` object before a Raphaël instance is created, otherwise it will take no effect.
318 | Raphael.fn.arrow = function (x1, y1, x2, y2, size) {
319 | return this.path( ... );
321 | // or create namespace
322 | Raphael.fn.mystuff = {
323 | arrow: function () {…},
324 | star: function () {…},
327 | var paper = Raphael(10, 10, 630, 480);
329 | paper.arrow(10, 10, 30, 30, 5).attr({fill: "#f00"});
330 | paper.mystuff.arrow();
331 | paper.mystuff.star();
333 R.fn = paperproto = Paper.prototype = R.prototype;
335 * Paper.customAttributes
336 [ property (object) ]
338 * If you have a set of attributes that you would like to represent
339 * as a function of some number you can do it easily with custom attributes:
341 | paper.customAttributes.hue = function (num) {
343 | return {fill: "hsb(" + num + ", .75, 1)"};
345 | // Custom attribute “hue” will change fill
346 | // to be given hue with fixed saturation and brightness.
347 | // Now you can use it like this:
348 | var c = paper.circle(10, 10, 10).attr({hue: .45});
349 | // or even like this:
350 | c.animate({hue: 1}, 1e3);
352 | // You could also create custom attribute
353 | // with multiple parameters:
354 | paper.customAttributes.hsb = function (h, s, b) {
355 | return {fill: "hsb(" + [h, s, b].join(",") + ")"};
357 | c.attr({hsb: ".5 .8 1"});
358 | c.animate({hsb: "1 0 .5"}, 1e3);
360 paperproto.customAttributes = {};
367 * Handfull replacement for `typeof` operator.
369 - o (…) any object or primitive
370 - type (string) name of the type, i.e. “string”, “function”, “number”, etc.
371 = (boolean) is given value is of given type
373 R.is = function (o, type) {
374 type = lowerCase.call(type);
375 if (type == "finite") {
376 return !isnan[has](+o);
378 if (type == "array") {
379 return o instanceof Array;
381 return (type == "null" && o === null) ||
382 (type == typeof o) ||
383 (type == "object" && o === Object(o)) ||
384 (type == "array" && Array.isArray && Array.isArray(o)) ||
385 objectToString.call(o).slice(8, -1).toLowerCase() == type;
391 * Returns angle between two or three points
393 - x1 (number) x coord of first point
394 - y1 (number) y coord of first point
395 - x2 (number) x coord of second point
396 - y2 (number) y coord of second point
397 - x3 (number) #optional x coord of third point
398 - y3 (number) #optional y coord of third point
399 = (number) angle in degrees.
401 R.angle = function (x1, y1, x2, y2, x3, y3) {
408 return (180 + math.atan2(-y, -x) * 180 / PI + 360) % 360;
410 return R.angle(x1, y1, x3, y3) - R.angle(x2, y2, x3, y3);
417 * Transform angle to radians
419 - deg (number) angle in degrees
420 = (number) angle in radians.
422 R.rad = function (deg) {
423 return deg % 360 * PI / 180;
429 * Transform angle to degrees
431 - deg (number) angle in radians
432 = (number) angle in degrees.
434 R.deg = function (rad) {
435 return rad * 180 / PI % 360;
441 * Snaps given value to given grid.
443 - values (array|number) given array of values or step of the grid
444 - value (number) value to adjust
445 - tolerance (number) #optional tolerance for snapping. Default is `10`.
446 = (number) adjusted value.
448 R.snapTo = function (values, value, tolerance) {
449 tolerance = R.is(tolerance, "finite") ? tolerance : 10;
450 if (R.is(values, array)) {
451 var i = values.length;
452 while (i--) if (abs(values[i] - value) <= tolerance) {
457 var rem = value % values;
458 if (rem < tolerance) {
461 if (rem > values - tolerance) {
462 return value - rem + values;
468 var createUUID = R._createUUID = (function (uuidRegEx, uuidReplacer) {
470 return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(uuidRegEx, uuidReplacer).toUpperCase();
472 })(/[xy]/g, function (c) {
473 var r = math.random() * 16 | 0,
474 v = c == "x" ? r : (r & 3 | 8);
475 return v.toString(16);
482 * Used when you need to draw in `<iframe>`. Switched window to the iframe one.
484 - newwin (window) new window object
486 R.setWindow = function (newwin) {
487 eve("setWindow", R, g.win, newwin);
489 g.doc = g.win.document;
495 var toHex = function (color) {
497 // http://dean.edwards.name/weblog/2009/10/convert-any-colour-value-to-hex-in-msie/
498 var trim = /^\s+|\s+$/g;
501 var docum = new ActiveXObject("htmlfile");
502 docum.write("<body>");
506 bod = createPopup().document.body;
508 var range = bod.createTextRange();
509 toHex = cacher(function (color) {
511 bod.style.color = Str(color).replace(trim, E);
512 var value = range.queryCommandValue("ForeColor");
513 value = ((value & 255) << 16) | (value & 65280) | ((value & 16711680) >>> 16);
514 return "#" + ("000000" + value.toString(16)).slice(-6);
520 var i = g.doc.createElement("i");
521 i.title = "Rapha\xebl Colour Picker";
522 i.style.display = "none";
523 g.doc.body.appendChild(i);
524 toHex = cacher(function (color) {
525 i.style.color = color;
526 return g.doc.defaultView.getComputedStyle(i, E).getPropertyValue("color");
531 hsbtoString = function () {
532 return "hsb(" + [this.h, this.s, this.b] + ")";
534 hsltoString = function () {
535 return "hsl(" + [this.h, this.s, this.l] + ")";
537 rgbtoString = function () {
540 prepareRGB = function (r, g, b) {
541 if (g == null && R.is(r, "object") && "r" in r && "g" in r && "b" in r) {
546 if (g == null && R.is(r, string)) {
547 var clr = R.getRGB(r);
552 if (r > 1 || g > 1 || b > 1) {
560 packageRGB = function (r, g, b, o) {
569 toString: rgbtoString
571 R.is(o, "finite") && (rgb.opacity = o);
579 * Parses the color string and returns object with all values for the given color.
581 - clr (string) color string in one of the supported formats (see @Raphael.getRGB)
582 = (object) Combined RGB & HSB object in format:
587 o hex (string) color in HTML/CSS format: #••••••,
588 o error (boolean) `true` if string can’t be parsed,
590 o s (number) saturation,
591 o v (number) value (brightness),
592 o l (number) lightness
595 R.color = function (clr) {
597 if (R.is(clr, "object") && "h" in clr && "s" in clr && "b" in clr) {
598 rgb = R.hsb2rgb(clr);
603 } else if (R.is(clr, "object") && "h" in clr && "s" in clr && "l" in clr) {
604 rgb = R.hsl2rgb(clr);
610 if (R.is(clr, "string")) {
613 if (R.is(clr, "object") && "r" in clr && "g" in clr && "b" in clr) {
614 rgb = R.rgb2hsl(clr);
618 rgb = R.rgb2hsb(clr);
622 crl.r = clr.g = clr.b = clr.h = clr.s = clr.v = clr.l = -1;
625 clr.toString = rgbtoString;
632 * Converts HSB values to RGB object.
635 - s (number) saturation
636 - v (number) value or brightness
637 = (object) RGB object in format:
642 o hex (string) color in HTML/CSS format: #••••••
645 R.hsb2rgb = function (h, s, v, o) {
646 if (this.is(h, "object") && "h" in h && "s" in h && "b" in h) {
656 X = C * (1 - abs(h % 2 - 1));
660 R += [C, X, 0, 0, X, C][h];
661 G += [X, C, C, X, 0, 0][h];
662 B += [0, 0, X, C, C, X][h];
663 return packageRGB(R, G, B, o);
669 * Converts HSL values to RGB object.
672 - s (number) saturation
673 - l (number) luminosity
674 = (object) RGB object in format:
679 o hex (string) color in HTML/CSS format: #••••••
682 R.hsl2rgb = function (h, s, l, o) {
683 if (this.is(h, "object") && "h" in h && "s" in h && "l" in h) {
688 if (h > 1 || s > 1 || l > 1) {
696 C = 2 * s * (l < .5 ? l : 1 - l);
697 X = C * (1 - abs(h % 2 - 1));
698 R = G = B = l - C / 2;
701 R += [C, X, 0, 0, X, C][h];
702 G += [X, C, C, X, 0, 0][h];
703 B += [0, 0, X, C, C, X][h];
704 return packageRGB(R, G, B, o);
710 * Converts RGB values to HSB object.
715 = (object) HSB object in format:
718 o s (number) saturation
719 o b (number) brightness
722 R.rgb2hsb = function (r, g, b) {
723 b = prepareRGB(r, g, b);
730 C = V - mmin(r, g, b);
732 V == r ? (g - b) / C :
733 V == g ? (b - r) / C + 2 :
736 H = ((H + 360) % 6) * 60 / 360;
737 S = C == 0 ? 0 : C / V;
738 return {h: H, s: S, b: V, toString: hsbtoString};
744 * Converts RGB values to HSL object.
749 = (object) HSL object in format:
752 o s (number) saturation
753 o l (number) luminosity
756 R.rgb2hsl = function (r, g, b) {
757 b = prepareRGB(r, g, b);
762 var H, S, L, M, m, C;
767 M == r ? (g - b) / C :
768 M == g ? (b - r) / C + 2 :
770 H = ((H + 360) % 6) * 60 / 360;
773 L < .5 ? C / (2 * L) :
775 return {h: H, s: S, l: L, toString: hsltoString};
777 R._path2string = function () {
778 return this.join(",").replace(p2s, "$1");
780 function repush(array, item) {
781 for (var i = 0, ii = array.length; i < ii; i++) if (array[i] === item) {
782 return array.push(array.splice(i, 1)[0]);
785 function cacher(f, scope, postprocessor) {
787 var arg = Array.prototype.slice.call(arguments, 0),
788 args = arg.join("\u2400"),
789 cache = newf.cache = newf.cache || {},
790 count = newf.count = newf.count || [];
791 if (cache[has](args)) {
793 return postprocessor ? postprocessor(cache[args]) : cache[args];
795 count.length >= 1e3 && delete cache[count.shift()];
797 cache[args] = f[apply](scope, arg);
798 return postprocessor ? postprocessor(cache[args]) : cache[args];
803 var preload = R._preload = function (src, f) {
804 var img = g.doc.createElement("img");
805 img.style.cssText = "position:absolute;left:-9999em;top-9999em";
806 img.onload = function () {
809 g.doc.body.removeChild(this);
811 img.onerror = function () {
812 g.doc.body.removeChild(this);
814 g.doc.body.appendChild(img);
818 function clrToString() {
826 * Parses colour string as RGB object
828 - colour (string) colour string in one of formats:
830 # <li>Colour name (“<code>red</code>”, “<code>green</code>”, “<code>cornflowerblue</code>”, etc)</li>
831 # <li>#••• — shortened HTML colour: (“<code>#000</code>”, “<code>#fc0</code>”, etc)</li>
832 # <li>#•••••• — full length HTML colour: (“<code>#000000</code>”, “<code>#bd2300</code>”)</li>
833 # <li>rgb(•••, •••, •••) — red, green and blue channels’ values: (“<code>rgb(200, 100, 0)</code>”)</li>
834 # <li>rgb(•••%, •••%, •••%) — same as above, but in %: (“<code>rgb(100%, 175%, 0%)</code>”)</li>
835 # <li>hsb(•••, •••, •••) — hue, saturation and brightness values: (“<code>hsb(0.5, 0.25, 1)</code>”)</li>
836 # <li>hsb(•••%, •••%, •••%) — same as above, but in %</li>
837 # <li>hsl(•••, •••, •••) — same as hsb</li>
838 # <li>hsl(•••%, •••%, •••%) — same as hsb</li>
840 = (object) RGB object in format:
845 o hex (string) color in HTML/CSS format: #••••••,
846 o error (boolean) true if string can’t be parsed
849 R.getRGB = cacher(function (colour) {
850 if (!colour || !!((colour = Str(colour)).indexOf("-") + 1)) {
851 return {r: -1, g: -1, b: -1, hex: "none", error: 1, toString: clrToString};
853 if (colour == "none") {
854 return {r: -1, g: -1, b: -1, hex: "none", toString: clrToString};
856 !(hsrg[has](colour.toLowerCase().substring(0, 2)) || colour.charAt() == "#") && (colour = toHex(colour));
864 rgb = colour.match(colourRegExp);
867 blue = toInt(rgb[2].substring(5), 16);
868 green = toInt(rgb[2].substring(3, 5), 16);
869 red = toInt(rgb[2].substring(1, 3), 16);
872 blue = toInt((t = rgb[3].charAt(3)) + t, 16);
873 green = toInt((t = rgb[3].charAt(2)) + t, 16);
874 red = toInt((t = rgb[3].charAt(1)) + t, 16);
877 values = rgb[4].split(commaSpaces);
878 red = toFloat(values[0]);
879 values[0].slice(-1) == "%" && (red *= 2.55);
880 green = toFloat(values[1]);
881 values[1].slice(-1) == "%" && (green *= 2.55);
882 blue = toFloat(values[2]);
883 values[2].slice(-1) == "%" && (blue *= 2.55);
884 rgb[1].toLowerCase().slice(0, 4) == "rgba" && (opacity = toFloat(values[3]));
885 values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
888 values = rgb[5].split(commaSpaces);
889 red = toFloat(values[0]);
890 values[0].slice(-1) == "%" && (red *= 2.55);
891 green = toFloat(values[1]);
892 values[1].slice(-1) == "%" && (green *= 2.55);
893 blue = toFloat(values[2]);
894 values[2].slice(-1) == "%" && (blue *= 2.55);
895 (values[0].slice(-3) == "deg" || values[0].slice(-1) == "\xb0") && (red /= 360);
896 rgb[1].toLowerCase().slice(0, 4) == "hsba" && (opacity = toFloat(values[3]));
897 values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
898 return R.hsb2rgb(red, green, blue, opacity);
901 values = rgb[6].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) == "hsla" && (opacity = toFloat(values[3]));
910 values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
911 return R.hsl2rgb(red, green, blue, opacity);
913 rgb = {r: red, g: green, b: blue, toString: clrToString};
914 rgb.hex = "#" + (16777216 | blue | (green << 8) | (red << 16)).toString(16).slice(1);
915 R.is(opacity, "finite") && (rgb.opacity = opacity);
918 return {r: -1, g: -1, b: -1, hex: "none", error: 1, toString: clrToString};
924 * Converts HSB values to hex representation of the colour.
927 - s (number) saturation
928 - b (number) value or brightness
929 = (string) hex representation of the colour.
931 R.hsb = cacher(function (h, s, b) {
932 return R.hsb2rgb(h, s, b).hex;
938 * Converts HSL values to hex representation of the colour.
941 - s (number) saturation
942 - l (number) luminosity
943 = (string) hex representation of the colour.
945 R.hsl = cacher(function (h, s, l) {
946 return R.hsl2rgb(h, s, l).hex;
952 * Converts RGB values to hex representation of the colour.
957 = (string) hex representation of the colour.
959 R.rgb = cacher(function (r, g, b) {
960 return "#" + (16777216 | b | (g << 8) | (r << 16)).toString(16).slice(1);
966 * On each call returns next colour in the spectrum. To reset it back to red call @Raphael.getColor.reset
968 - value (number) #optional brightness, default is `0.75`
969 = (string) hex representation of the colour.
971 R.getColor = function (value) {
972 var start = this.getColor.start = this.getColor.start || {h: 0, s: 1, b: value || .75},
973 rgb = this.hsb2rgb(start.h, start.s, start.b);
978 start.s <= 0 && (this.getColor.start = {h: 0, s: 1, b: start.b});
983 * Raphael.getColor.reset
986 * Resets spectrum position for @Raphael.getColor back to red.
988 R.getColor.reset = function () {
993 * Raphael.parsePathString
998 * Parses given path string into an array of arrays of path segments.
1000 - pathString (string|array) path string or array of segments (in the last case it will be returned straight away)
1001 = (array) array of segments.
1003 R.parsePathString = cacher(function (pathString) {
1007 var paramCounts = {a: 7, c: 6, h: 1, l: 2, m: 2, q: 4, s: 4, t: 2, v: 1, z: 0},
1009 if (R.is(pathString, array) && R.is(pathString[0], array)) { // rough assumption
1010 data = pathClone(pathString);
1013 Str(pathString).replace(pathCommand, function (a, b, c) {
1015 name = lowerCase.call(b);
1016 c.replace(pathValues, function (a, b) {
1017 b && params.push(+b);
1019 if (name == "m" && params.length > 2) {
1020 data.push([b][concat](params.splice(0, 2)));
1022 b = b == "m" ? "l" : "L";
1024 while (params.length >= paramCounts[name]) {
1025 data.push([b][concat](params.splice(0, paramCounts[name])));
1026 if (!paramCounts[name]) {
1032 data.toString = R._path2string;
1036 * Raphael.parseTransformString
1041 * Parses given path string into an array of transformations.
1043 - TString (string|array) transform string or array of transformations (in the last case it will be returned straight away)
1044 = (array) array of transformations.
1046 R.parseTransformString = cacher(function (TString) {
1050 var paramCounts = {r: 3, s: 4, t: 2, m: 6},
1052 if (R.is(TString, array) && R.is(TString[0], array)) { // rough assumption
1053 data = pathClone(TString);
1056 Str(TString).replace(tCommand, function (a, b, c) {
1058 name = lowerCase.call(b);
1059 c.replace(pathValues, function (a, b) {
1060 b && params.push(+b);
1062 data.push([name][concat](params));
1065 data.toString = R._path2string;
1069 * Raphael.findDotsAtSegment
1074 * Find dot coordinates on the given cubic bezier curve at the given t.
1076 - p1x (number) x of the first point of the curve
1077 - p1y (number) y of the first point of the curve
1078 - c1x (number) x of the first anchor of the curve
1079 - c1y (number) y of the first anchor of the curve
1080 - c2x (number) x of the second anchor of the curve
1081 - c2y (number) y of the second anchor of the curve
1082 - p2x (number) x of the second point of the curve
1083 - p2y (number) y of the second point of the curve
1084 - t (number) position on the curve (0..1)
1085 = (object) point information in format:
1087 o x: (number) x coordinate of the point
1088 o y: (number) y coordinate of the point
1090 o x: (number) x coordinate of the left anchor
1091 o y: (number) y coordinate of the left anchor
1094 o x: (number) x coordinate of the right anchor
1095 o y: (number) y coordinate of the right anchor
1098 o x: (number) x coordinate of the start of the curve
1099 o y: (number) y coordinate of the start of the curve
1102 o x: (number) x coordinate of the end of the curve
1103 o y: (number) y coordinate of the end of the curve
1105 o alpha: (number) angle of the curve derivative at the point
1108 R.findDotsAtSegment = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) {
1110 x = pow(t1, 3) * p1x + pow(t1, 2) * 3 * t * c1x + t1 * 3 * t * t * c2x + pow(t, 3) * p2x,
1111 y = pow(t1, 3) * p1y + pow(t1, 2) * 3 * t * c1y + t1 * 3 * t * t * c2y + pow(t, 3) * p2y,
1112 mx = p1x + 2 * t * (c1x - p1x) + t * t * (c2x - 2 * c1x + p1x),
1113 my = p1y + 2 * t * (c1y - p1y) + t * t * (c2y - 2 * c1y + p1y),
1114 nx = c1x + 2 * t * (c2x - c1x) + t * t * (p2x - 2 * c2x + c1x),
1115 ny = c1y + 2 * t * (c2y - c1y) + t * t * (p2y - 2 * c2y + c1y),
1116 ax = (1 - t) * p1x + t * c1x,
1117 ay = (1 - t) * p1y + t * c1y,
1118 cx = (1 - t) * c2x + t * p2x,
1119 cy = (1 - t) * c2y + t * p2y,
1120 alpha = (90 - math.atan2(mx - nx, my - ny) * 180 / PI);
1121 (mx > nx || my < ny) && (alpha += 180);
1127 start: {x: ax, y: ay},
1128 end: {x: cx, y: cy},
1132 var pathDimensions = cacher(function (path) {
1134 return {x: 0, y: 0, width: 0, height: 0};
1136 path = path2curve(path);
1142 for (var i = 0, ii = path.length; i < ii; i++) {
1150 var dim = curveDim(x, y, p[1], p[2], p[3], p[4], p[5], p[6]);
1151 X = X[concat](dim.min.x, dim.max.x);
1152 Y = Y[concat](dim.min.y, dim.max.y);
1157 var xmin = mmin[apply](0, X),
1158 ymin = mmin[apply](0, Y);
1162 width: mmax[apply](0, X) - xmin,
1163 height: mmax[apply](0, Y) - ymin
1165 }, null, function (o) {
1173 pathClone = function (pathArray) {
1175 if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) { // rough assumption
1176 pathArray = R.parsePathString(pathArray);
1178 for (var i = 0, ii = pathArray.length; i < ii; i++) {
1180 for (var j = 0, jj = pathArray[i].length; j < jj; j++) {
1181 res[i][j] = pathArray[i][j];
1184 res.toString = R._path2string;
1187 pathToRelative = R._pathToRelative = cacher(function (pathArray) {
1188 if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) { // rough assumption
1189 pathArray = R.parsePathString(pathArray);
1197 if (pathArray[0][0] == "M") {
1198 x = pathArray[0][1];
1199 y = pathArray[0][2];
1203 res.push(["M", x, y]);
1205 for (var i = start, ii = pathArray.length; i < ii; i++) {
1206 var r = res[i] = [],
1208 if (pa[0] != lowerCase.call(pa[0])) {
1209 r[0] = lowerCase.call(pa[0]);
1217 r[6] = +(pa[6] - x).toFixed(3);
1218 r[7] = +(pa[7] - y).toFixed(3);
1221 r[1] = +(pa[1] - y).toFixed(3);
1227 for (var j = 1, jj = pa.length; j < jj; j++) {
1228 r[j] = +(pa[j] - ((j % 2) ? x : y)).toFixed(3);
1237 for (var k = 0, kk = pa.length; k < kk; k++) {
1241 var len = res[i].length;
1242 switch (res[i][0]) {
1248 x += +res[i][len - 1];
1251 y += +res[i][len - 1];
1254 x += +res[i][len - 2];
1255 y += +res[i][len - 1];
1258 res.toString = R._path2string;
1261 pathToAbsolute = R._pathToAbsolute = cacher(function (pathArray) {
1262 if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) { // rough assumption
1263 pathArray = R.parsePathString(pathArray);
1265 if (!pathArray || !pathArray.length) {
1266 return [["M", 0, 0]];
1274 if (pathArray[0][0] == "M") {
1275 x = +pathArray[0][1];
1276 y = +pathArray[0][2];
1280 res[0] = ["M", x, y];
1282 for (var i = start, ii = pathArray.length; i < ii; i++) {
1283 var r = res[i] = [],
1285 if (pa[0] != upperCase.call(pa[0])) {
1286 r[0] = upperCase.call(pa[0]);
1294 r[6] = +(pa[6] + x);
1295 r[7] = +(pa[7] + y);
1307 for (var j = 1, jj = pa.length; j < jj; j++) {
1308 r[j] = +pa[j] + ((j % 2) ? x : y);
1312 for (var k = 0, kk = pa.length; k < kk; k++) {
1328 mx = res[i][res[i].length - 2];
1329 my = res[i][res[i].length - 1];
1331 x = res[i][res[i].length - 2];
1332 y = res[i][res[i].length - 1];
1335 res.toString = R._path2string;
1337 }, null, pathClone),
1338 l2c = function (x1, y1, x2, y2) {
1339 return [x1, y1, x2, y2, x2, y2];
1341 q2c = function (x1, y1, ax, ay, x2, y2) {
1345 _13 * x1 + _23 * ax,
1346 _13 * y1 + _23 * ay,
1347 _13 * x2 + _23 * ax,
1348 _13 * y2 + _23 * ay,
1353 a2c = function (x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursive) {
1354 // for more information of where this math came from visit:
1355 // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
1356 var _120 = PI * 120 / 180,
1357 rad = PI / 180 * (+angle || 0),
1360 rotate = cacher(function (x, y, rad) {
1361 var X = x * math.cos(rad) - y * math.sin(rad),
1362 Y = x * math.sin(rad) + y * math.cos(rad);
1363 return {x: X, y: Y};
1366 xy = rotate(x1, y1, -rad);
1369 xy = rotate(x2, y2, -rad);
1372 var cos = math.cos(PI / 180 * angle),
1373 sin = math.sin(PI / 180 * angle),
1376 var h = (x * x) / (rx * rx) + (y * y) / (ry * ry);
1384 k = (large_arc_flag == sweep_flag ? -1 : 1) *
1385 math.sqrt(abs((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x))),
1386 cx = k * rx * y / ry + (x1 + x2) / 2,
1387 cy = k * -ry * x / rx + (y1 + y2) / 2,
1388 f1 = math.asin(((y1 - cy) / ry).toFixed(9)),
1389 f2 = math.asin(((y2 - cy) / ry).toFixed(9));
1391 f1 = x1 < cx ? PI - f1 : f1;
1392 f2 = x2 < cx ? PI - f2 : f2;
1393 f1 < 0 && (f1 = PI * 2 + f1);
1394 f2 < 0 && (f2 = PI * 2 + f2);
1395 if (sweep_flag && f1 > f2) {
1398 if (!sweep_flag && f2 > f1) {
1408 if (abs(df) > _120) {
1412 f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1);
1413 x2 = cx + rx * math.cos(f2);
1414 y2 = cy + ry * math.sin(f2);
1415 res = a2c(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [f2, f2old, cx, cy]);
1418 var c1 = math.cos(f1),
1422 t = math.tan(df / 4),
1423 hx = 4 / 3 * rx * t,
1424 hy = 4 / 3 * ry * t,
1426 m2 = [x1 + hx * s1, y1 - hy * c1],
1427 m3 = [x2 + hx * s2, y2 - hy * c2],
1429 m2[0] = 2 * m1[0] - m2[0];
1430 m2[1] = 2 * m1[1] - m2[1];
1432 return [m2, m3, m4][concat](res);
1434 res = [m2, m3, m4][concat](res).join().split(",");
1436 for (var i = 0, ii = res.length; i < ii; i++) {
1437 newres[i] = i % 2 ? rotate(res[i - 1], res[i], rad).y : rotate(res[i], res[i + 1], rad).x;
1442 findDotAtSegment = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) {
1445 x: pow(t1, 3) * p1x + pow(t1, 2) * 3 * t * c1x + t1 * 3 * t * t * c2x + pow(t, 3) * p2x,
1446 y: pow(t1, 3) * p1y + pow(t1, 2) * 3 * t * c1y + t1 * 3 * t * t * c2y + pow(t, 3) * p2y
1449 curveDim = cacher(function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) {
1450 var a = (c2x - 2 * c1x + p1x) - (p2x - 2 * c2x + c1x),
1451 b = 2 * (c1x - p1x) - 2 * (c2x - c1x),
1453 t1 = (-b + math.sqrt(b * b - 4 * a * c)) / 2 / a,
1454 t2 = (-b - math.sqrt(b * b - 4 * a * c)) / 2 / a,
1458 abs(t1) > "1e12" && (t1 = .5);
1459 abs(t2) > "1e12" && (t2 = .5);
1460 if (t1 > 0 && t1 < 1) {
1461 dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t1);
1465 if (t2 > 0 && t2 < 1) {
1466 dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t2);
1470 a = (c2y - 2 * c1y + p1y) - (p2y - 2 * c2y + c1y);
1471 b = 2 * (c1y - p1y) - 2 * (c2y - c1y);
1473 t1 = (-b + math.sqrt(b * b - 4 * a * c)) / 2 / a;
1474 t2 = (-b - math.sqrt(b * b - 4 * a * c)) / 2 / a;
1475 abs(t1) > "1e12" && (t1 = .5);
1476 abs(t2) > "1e12" && (t2 = .5);
1477 if (t1 > 0 && t1 < 1) {
1478 dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t1);
1482 if (t2 > 0 && t2 < 1) {
1483 dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t2);
1488 min: {x: mmin[apply](0, x), y: mmin[apply](0, y)},
1489 max: {x: mmax[apply](0, x), y: mmax[apply](0, y)}
1492 path2curve = cacher(function (path, path2) {
1493 var p = pathToAbsolute(path),
1494 p2 = path2 && pathToAbsolute(path2),
1495 attrs = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null},
1496 attrs2 = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null},
1497 processPath = function (path, d) {
1500 return ["C", d.x, d.y, d.x, d.y, d.x, d.y];
1502 !(path[0] in {T:1, Q:1}) && (d.qx = d.qy = null);
1509 path = ["C"][concat](a2c[apply](0, [d.x, d.y][concat](path.slice(1))));
1512 nx = d.x + (d.x - (d.bx || d.x));
1513 ny = d.y + (d.y - (d.by || d.y));
1514 path = ["C", nx, ny][concat](path.slice(1));
1517 d.qx = d.x + (d.x - (d.qx || d.x));
1518 d.qy = d.y + (d.y - (d.qy || d.y));
1519 path = ["C"][concat](q2c(d.x, d.y, d.qx, d.qy, path[1], path[2]));
1524 path = ["C"][concat](q2c(d.x, d.y, path[1], path[2], path[3], path[4]));
1527 path = ["C"][concat](l2c(d.x, d.y, path[1], path[2]));
1530 path = ["C"][concat](l2c(d.x, d.y, path[1], d.y));
1533 path = ["C"][concat](l2c(d.x, d.y, d.x, path[1]));
1536 path = ["C"][concat](l2c(d.x, d.y, d.X, d.Y));
1541 fixArc = function (pp, i) {
1542 if (pp[i].length > 7) {
1546 pp.splice(i++, 0, ["C"][concat](pi.splice(0, 6)));
1549 ii = mmax(p.length, p2 && p2.length || 0);
1552 fixM = function (path1, path2, a1, a2, i) {
1553 if (path1 && path2 && path1[i][0] == "M" && path2[i][0] != "M") {
1554 path2.splice(i, 0, ["M", a2.x, a2.y]);
1559 ii = mmax(p.length, p2 && p2.length || 0);
1562 for (var i = 0, ii = mmax(p.length, p2 && p2.length || 0); i < ii; i++) {
1563 p[i] = processPath(p[i], attrs);
1565 p2 && (p2[i] = processPath(p2[i], attrs2));
1566 p2 && fixArc(p2, i);
1567 fixM(p, p2, attrs, attrs2, i);
1568 fixM(p2, p, attrs2, attrs, i);
1571 seglen = seg.length,
1572 seg2len = p2 && seg2.length;
1573 attrs.x = seg[seglen - 2];
1574 attrs.y = seg[seglen - 1];
1575 attrs.bx = toFloat(seg[seglen - 4]) || attrs.x;
1576 attrs.by = toFloat(seg[seglen - 3]) || attrs.y;
1577 attrs2.bx = p2 && (toFloat(seg2[seg2len - 4]) || attrs2.x);
1578 attrs2.by = p2 && (toFloat(seg2[seg2len - 3]) || attrs2.y);
1579 attrs2.x = p2 && seg2[seg2len - 2];
1580 attrs2.y = p2 && seg2[seg2len - 1];
1582 return p2 ? [p, p2] : p;
1583 }, null, pathClone),
1584 parseDots = R._parseDots = cacher(function (gradient) {
1586 for (var i = 0, ii = gradient.length; i < ii; i++) {
1588 par = gradient[i].match(/^([^:]*):?([\d\.]*)/);
1589 dot.color = R.getRGB(par[1]);
1590 if (dot.color.error) {
1593 dot.color = dot.color.hex;
1594 par[2] && (dot.offset = par[2] + "%");
1597 for (i = 1, ii = dots.length - 1; i < ii; i++) {
1598 if (!dots[i].offset) {
1599 var start = toFloat(dots[i - 1].offset || 0),
1601 for (var j = i + 1; j < ii; j++) {
1602 if (dots[j].offset) {
1603 end = dots[j].offset;
1612 var d = (end - start) / (j - i + 1);
1613 for (; i < j; i++) {
1615 dots[i].offset = start + "%";
1621 tear = R._tear = function (el, paper) {
1622 el == paper.top && (paper.top = el.prev);
1623 el == paper.bottom && (paper.bottom = el.next);
1624 el.next && (el.next.prev = el.prev);
1625 el.prev && (el.prev.next = el.next);
1627 tofront = R._tofront = function (el, paper) {
1628 if (paper.top === el) {
1633 el.prev = paper.top;
1634 paper.top.next = el;
1637 toback = R._toback = function (el, paper) {
1638 if (paper.bottom === el) {
1642 el.next = paper.bottom;
1644 paper.bottom.prev = el;
1647 insertafter = R._insertafter = function (el, el2, paper) {
1649 el2 == paper.top && (paper.top = el);
1650 el2.next && (el2.next.prev = el);
1655 insertbefore = R._insertbefore = function (el, el2, paper) {
1657 el2 == paper.bottom && (paper.bottom = el);
1658 el2.prev && (el2.prev.next = el);
1663 removed = function (methodname) {
1664 return function () {
1665 throw new Error("Rapha\xebl: you are calling to method \u201c" + methodname + "\u201d of removed object");
1668 extractTransform = R._extractTransform = function (el, tstr) {
1670 return el._.transform;
1672 tstr = Str(tstr).replace(/\.{3}|\u2026/g, el._.transform || E);
1673 var tdata = R.parseTransformString(tstr),
1681 _.transform = tdata || [];
1683 for (var i = 0, ii = tdata.length; i < ii; i++) {
1687 t[0] = Str(t[0]).toLowerCase();
1688 if (t[0] == "t" && tlen == 3) {
1689 m.translate(t[1], t[2]);
1690 } else if (t[0] == "r") {
1692 bb = bb || el.getBBox(1);
1693 m.rotate(t[1], bb.x + bb.width / 2, bb.y + bb.height / 2);
1695 } else if (tlen == 4) {
1696 m.rotate(t[1], t[2], t[3]);
1699 } else if (t[0] == "s") {
1700 if (tlen == 2 || tlen == 3) {
1701 bb = bb || el.getBBox(1);
1702 m.scale(t[1], t[tlen - 1], bb.x + bb.width / 2, bb.y + bb.height / 2);
1705 } else if (tlen == 5) {
1706 m.scale(t[1], t[2], t[3], t[4]);
1710 } else if (t[0] == "m" && tlen == 7) {
1711 m.add(t[1], t[2], t[3], t[4], t[5], t[6]);
1726 if (sx == 1 && sy == 1 && !deg && _.bbox) {
1733 getEmpty = function (item) {
1735 case "t": return ["t", 0, 0];
1736 case "m": return ["m", 1, 0, 0, 1, 0, 0];
1737 case "r": if (item.length == 4) {
1738 return ["r", 0, item[2], item[3]];
1742 case "s": if (item.length == 5) {
1743 return ["s", 1, 1, item[3], item[4]];
1744 } else if (item.length == 3) {
1751 equaliseTransform = R._equaliseTransform = function (t1, t2) {
1752 t2 = Str(t2).replace(/\.{3}|\u2026/g, t1);
1753 t1 = R.parseTransformString(t1) || [];
1754 t2 = R.parseTransformString(t2) || [];
1755 var maxlength = mmax(t1.length, t2.length),
1760 for (; i < maxlength; i++) {
1761 tt1 = t1[i] || getEmpty(t2[i]);
1762 tt2 = t2[i] || getEmpty(tt1);
1763 if ((tt1[0] != tt2[0]) ||
1764 (tt1[0] == "r" && (tt1[2] != tt2[2] || tt1[3] != tt2[3])) ||
1765 (tt1[0] == "s" && (tt1[3] != tt2[3] || tt1[4] != tt2[4]))
1771 for (j = 0, jj = mmax(tt1.length, tt2.length); j < jj; j++) {
1772 j in tt1 && (from[i][j] = tt1[j]);
1773 j in tt2 && (to[i][j] = tt2[j]);
1781 R._getContainer = function (x, y, w, h) {
1783 container = h == null && !R.is(x, "object") ? g.doc.getElementById(x) : x;
1784 if (container == null) {
1787 if (container.tagName) {
1790 container: container,
1791 width: container.style.pixelWidth || container.offsetWidth,
1792 height: container.style.pixelHeight || container.offsetHeight
1796 container: container,
1811 * Raphael.pathToRelative
1816 * Converts path to relative form
1818 - pathString (string|array) path string or array of segments
1819 = (array) array of segments.
1821 R.pathToRelative = pathToRelative;
1824 * Raphael.path2curve
1829 * Converts path to a new path where all segments are cubic bezier curves.
1831 - pathString (string|array) path string or array of segments
1832 = (array) array of segments.
1834 R.path2curve = path2curve;
1841 * Returns matrix based on given parameters.
1851 R.matrix = function (a, b, c, d, e, f) {
1852 return new Matrix(a, b, c, d, e, f);
1854 function Matrix(a, b, c, d, e, f) {
1871 (function (matrixproto) {
1872 matrixproto.add = function (a, b, c, d, e, f) {
1873 var out = [[], [], []],
1874 m = [[this.a, this.c, this.e], [this.b, this.d, this.f], [0, 0, 1]],
1875 matrix = [[a, c, e], [b, d, f], [0, 0, 1]],
1878 if (a && a instanceof Matrix) {
1879 matrix = [[a.a, a.c, a.e], [a.b, a.d, a.f], [0, 0, 1]];
1882 for (x = 0; x < 3; x++) {
1883 for (y = 0; y < 3; y++) {
1885 for (z = 0; z < 3; z++) {
1886 res += m[x][z] * matrix[z][y];
1898 matrixproto.invert = function () {
1900 x = me.a * me.d - me.b * me.c;
1901 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);
1903 matrixproto.clone = function () {
1904 return new Matrix(this.a, this.b, this.c, this.d, this.e, this.f);
1906 matrixproto.translate = function (x, y) {
1907 this.add(1, 0, 0, 1, x, y);
1909 matrixproto.scale = function (x, y, cx, cy) {
1910 y == null && (y = x);
1911 this.add(1, 0, 0, 1, cx, cy);
1912 this.add(x, 0, 0, y, 0, 0);
1913 this.add(1, 0, 0, 1, -cx, -cy);
1915 matrixproto.rotate = function (a, x, y) {
1917 var cos = +math.cos(a).toFixed(9),
1918 sin = +math.sin(a).toFixed(9);
1919 this.add(cos, sin, -sin, cos, x, y);
1920 this.add(1, 0, 0, 1, -x, -y);
1922 matrixproto.x = function (x, y) {
1923 return x * this.a + y * this.c + this.e;
1925 matrixproto.y = function (x, y) {
1926 return x * this.b + y * this.d + this.f;
1928 matrixproto.get = function (i) {
1929 return +this[Str.fromCharCode(97 + i)].toFixed(4);
1931 matrixproto.toString = function () {
1933 "matrix(" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)].join() + ")" :
1934 [this.get(0), this.get(2), this.get(1), this.get(3), 0, 0].join();
1936 matrixproto.toFilter = function () {
1937 return "progid:DXImageTransform.Microsoft.Matrix(M11=" + this.get(0) +
1938 ", M12=" + this.get(2) + ", M21=" + this.get(1) + ", M22=" + this.get(3) +
1939 ", Dx=" + this.get(4) + ", Dy=" + this.get(5) + ", sizingmethod='auto expand')";
1941 matrixproto.offset = function () {
1942 return [this.e.toFixed(4), this.f.toFixed(4)];
1945 return a[0] * a[0] + a[1] * a[1];
1947 function normalize(a) {
1948 var mag = math.sqrt(norm(a));
1949 a[0] && (a[0] /= mag);
1950 a[1] && (a[1] /= mag);
1952 matrixproto.split = function () {
1959 var row = [[this.a, this.c], [this.b, this.d]];
1960 out.scalex = math.sqrt(norm(row[0]));
1963 out.shear = row[0][0] * row[1][0] + row[0][1] * row[1][1];
1964 row[1] = [row[1][0] - row[0][0] * out.shear, row[1][1] - row[0][1] * out.shear];
1966 out.scaley = math.sqrt(norm(row[1]));
1968 out.shear /= out.scaley;
1971 var sin = -row[0][1],
1974 out.rotate = R.deg(math.acos(cos));
1976 out.rotate = 360 - out.rotate;
1979 out.rotate = R.deg(math.asin(sin));
1982 out.isSimple = !+out.shear.toFixed(9) && (out.scalex.toFixed(9) == out.scaley.toFixed(9) || !out.rotate);
1983 out.isSuperSimple = !+out.shear.toFixed(9) && out.scalex.toFixed(9) == out.scaley.toFixed(9) && !out.rotate;
1984 out.noRotation = !+out.shear.toFixed(9) && !out.rotate;
1987 matrixproto.toTransformString = function () {
1988 var s = this.split();
1990 return "t" + [s.dx, s.dy] + "s" + [s.scalex, s.scaley, 0, 0] + "r" + [s.rotate, 0, 0];
1992 return "m" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)];
1995 })(Matrix.prototype);
1997 // WebKit rendering bug workaround method
1998 var version = navigator.userAgent.match(/Version\/(.*?)\s/) || navigator.userAgent.match(/Chrome\/(\d+)/);
1999 if ((navigator.vendor == "Apple Computer, Inc.") && (version && version[1] < 4 || navigator.platform.slice(0, 2) == "iP") ||
2000 (navigator.vendor == "Google Inc." && version && version[1] < 8)) {
2005 * There is an inconvenient rendering bug in Safari (WebKit):
2006 * sometimes the rendering should be forced.
2007 * This method should help with dealing with this bug.
2009 paperproto.safari = function () {
2010 var rect = this.rect(-99, -99, this.width + 99, this.height + 99).attr({stroke: "none"});
2011 setTimeout(function () {rect.remove();});
2014 paperproto.safari = fun;
2018 var preventDefault = function () {
2019 this.returnValue = false;
2021 preventTouch = function () {
2022 return this.originalEvent.preventDefault();
2024 stopPropagation = function () {
2025 this.cancelBubble = true;
2027 stopTouch = function () {
2028 return this.originalEvent.stopPropagation();
2030 addEvent = (function () {
2031 if (g.doc.addEventListener) {
2032 return function (obj, type, fn, element) {
2033 var realName = supportsTouch && touchMap[type] ? touchMap[type] : type,
2035 var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
2036 scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft,
2037 x = e.clientX + scrollX,
2038 y = e.clientY + scrollY;
2039 if (supportsTouch && touchMap[has](type)) {
2040 for (var i = 0, ii = e.targetTouches && e.targetTouches.length; i < ii; i++) {
2041 if (e.targetTouches[i].target == obj) {
2043 e = e.targetTouches[i];
2044 e.originalEvent = olde;
2045 e.preventDefault = preventTouch;
2046 e.stopPropagation = stopTouch;
2051 return fn.call(element, e, x, y);
2053 obj.addEventListener(realName, f, false);
2054 return function () {
2055 obj.removeEventListener(realName, f, false);
2059 } else if (g.doc.attachEvent) {
2060 return function (obj, type, fn, element) {
2061 var f = function (e) {
2062 e = e || g.win.event;
2063 var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
2064 scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft,
2065 x = e.clientX + scrollX,
2066 y = e.clientY + scrollY;
2067 e.preventDefault = e.preventDefault || preventDefault;
2068 e.stopPropagation = e.stopPropagation || stopPropagation;
2069 return fn.call(element, e, x, y);
2071 obj.attachEvent("on" + type, f);
2072 var detacher = function () {
2073 obj.detachEvent("on" + type, f);
2081 dragMove = function (e) {
2084 scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
2085 scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft,
2090 if (supportsTouch) {
2091 var i = e.touches.length,
2094 touch = e.touches[i];
2095 if (touch.identifier == dragi.el._drag.id) {
2098 (e.originalEvent ? e.originalEvent : e).preventDefault();
2105 var node = dragi.el.node,
2107 next = node.nextSibling,
2108 parent = node.parentNode,
2109 display = node.style.display;
2110 g.win.opera && parent.removeChild(node);
2111 node.style.display = "none";
2112 o = dragi.el.paper.getElementByPoint(x, y);
2113 node.style.display = display;
2114 g.win.opera && (next ? parent.insertBefore(node, next) : parent.appendChild(node));
2115 o && eve("drag.over." + dragi.el.id, dragi.el, o);
2118 eve("drag.move." + dragi.el.id, dragi.move_scope || dragi.el, x - dragi.el._drag.x, y - dragi.el._drag.y, x, y, e);
2121 dragUp = function (e) {
2122 R.unmousemove(dragMove).unmouseup(dragUp);
2123 var i = drag.length,
2127 dragi.el._drag = {};
2128 eve("drag.end." + dragi.el.id, dragi.end_scope || dragi.start_scope || dragi.move_scope || dragi.el, e);
2134 [ property (object) ]
2136 * You can add your own method to elements. This is usefull when you want to hack default functionality or
2137 * want to wrap some common transformation or attributes in one method. In difference to canvas methods,
2138 * you can redefine element method at any time. Expending element methods wouldn’t affect set.
2140 | Raphael.el.red = function () {
2141 | this.attr({fill: "#f00"});
2144 | paper.circle(100, 100, 20).red();
2146 elproto = R.el = {};
2147 for (var i = events.length; i--;) {
2148 (function (eventName) {
2149 R[eventName] = elproto[eventName] = function (fn, scope) {
2150 if (R.is(fn, "function")) {
2151 this.events = this.events || [];
2152 this.events.push({name: eventName, f: fn, unbind: addEvent(this.shape || this.node || g.doc, eventName, fn, scope || this)});
2156 R["un" + eventName] = elproto["un" + eventName] = function (fn) {
2157 var events = this.events,
2159 while (l--) if (events[l].name == eventName && events[l].f == fn) {
2161 events.splice(l, 1);
2162 !events.length && delete this.events;
2174 * Adds event handlers for hover for the element.
2176 - f_in (function) handler for hover in
2177 - f_out (function) handler for hover out
2178 - icontext (object) #optional context for hover in handler
2179 - ocontext (object) #optional context for hover out handler
2182 elproto.hover = function (f_in, f_out, scope_in, scope_out) {
2183 return this.mouseover(f_in, scope_in).mouseout(f_out, scope_out || scope_in);
2189 * Removes event handlers for hover for the element.
2191 - f_in (function) handler for hover in
2192 - f_out (function) handler for hover out
2195 elproto.unhover = function (f_in, f_out) {
2196 return this.unmouseover(f_in).unmouseout(f_out);
2202 * Adds event handlers for drag of the element.
2204 - onmove (function) handler for moving
2205 - onstart (function) handler for drag start
2206 - onend (function) handler for drag end
2207 - mcontext (object) #optional context for moving handler
2208 - scontext (object) #optional context for drag start handler
2209 - econtext (object) #optional context for drag end handler
2210 * Additionaly following `drag` events will be triggered: `drag.start.<id>` on start,
2211 * `drag.end.<id>` on end and `drag.move.<id>` on every move. When element will be dragged over another element
2212 * `drag.over.<id>` will be fired as well.
2214 * Start event and start handler will be called in specified context or in context of the element with following parameters:
2215 o x (number) x position of the mouse
2216 o y (number) y position of the mouse
2217 o event (object) DOM event object
2218 * Move event and move handler will be called in specified context or in context of the element with following parameters:
2219 o dx (number) shift by x from the start point
2220 o dy (number) shift by y from the start point
2221 o x (number) x position of the mouse
2222 o y (number) y position of the mouse
2223 o event (object) DOM event object
2224 * End event and end handler will be called in specified context or in context of the element with following parameters:
2225 o event (object) DOM event object
2228 elproto.drag = function (onmove, onstart, onend, move_scope, start_scope, end_scope) {
2230 (e.originalEvent || e).preventDefault();
2231 var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
2232 scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft;
2233 this._drag.x = e.clientX + scrollX;
2234 this._drag.y = e.clientY + scrollY;
2235 this._drag.id = e.identifier;
2236 !drag.length && R.mousemove(dragMove).mouseup(dragUp);
2237 drag.push({el: this, move_scope: move_scope, start_scope: start_scope, end_scope: end_scope});
2238 onstart && eve.on("drag.start." + this.id, onstart);
2239 onmove && eve.on("drag.move." + this.id, onmove);
2240 onend && eve.on("drag.end." + this.id, onend);
2241 eve("drag.start." + this.id, start_scope || move_scope || this, e.clientX + scrollX, e.clientY + scrollY, e);
2244 this.mousedown(start);
2248 * Element.onDragOver
2251 * Shortcut for assigning event handler for `drag.over.<id>` event, where id is id of the element (see @Element.id).
2253 - f (function) handler for event
2255 elproto.onDragOver = function (f) {
2256 f ? eve.on("drag.over." + this.id, f) : eve.unbind("drag.over." + this.id);
2262 * Removes all drag event handlers from given element.
2264 elproto.undrag = function () {
2265 var i = drag.length;
2266 while (i--) if (drag[i].el == this) {
2267 R.unmousedown(drag[i].start);
2268 drag.splice(i++, 1);
2269 eve.unbind("drag.*." + this.id);
2271 !drag.length && R.unmousemove(dragMove).unmouseup(dragUp);
2281 - x (number) x coordinate of the centre
2282 - y (number) y coordinate of the centre
2284 = (object) Raphaël element object with type “circle”
2287 | var c = paper.circle(50, 50, 40);
2289 paperproto.circle = function (x, y, r) {
2290 var out = R._engine.circle(this, x || 0, y || 0, r || 0);
2291 this.__set__ && this.__set__.push(out);
2298 * Draws a rectangle.
2302 - x (number) x coordinate of the top left corner
2303 - y (number) y coordinate of the top left corner
2304 - width (number) width
2305 - height (number) height
2306 - r (number) #optional radius for rounded corners, default is 0
2307 = (object) Raphaël element object with type “rect”
2310 | // regular rectangle
2311 | var c = paper.rect(10, 10, 50, 50);
2312 | // rectangle with rounded corners
2313 | var c = paper.rect(40, 40, 50, 50, 10);
2315 paperproto.rect = function (x, y, w, h, r) {
2316 var out = R._engine.rect(this, x || 0, y || 0, w || 0, h || 0, r || 0);
2317 this.__set__ && this.__set__.push(out);
2328 - x (number) x coordinate of the centre
2329 - y (number) y coordinate of the centre
2330 - rx (number) horizontal radius
2331 - ry (number) vertical radius
2332 = (object) Raphaël element object with type “ellipse”
2335 | var c = paper.ellipse(50, 50, 40, 20);
2337 paperproto.ellipse = function (x, y, rx, ry) {
2338 var out = R._engine.ellipse(this, x || 0, y || 0, rx || 0, ry || 0);
2339 this.__set__ && this.__set__.push(out);
2346 * Creates a path element by given path data string.
2350 - pathString (string) path data in SVG path string format.
2351 = (object) Raphaël element object with type “path”
2352 # Details of a path's data attribute's format are described in the <a href="http://www.w3.org/TR/SVG/paths.html#PathData">SVG specification</a>.
2355 | var c = paper.path("M10 10L90 90");
2356 | // draw a diagonal line:
2357 | // move to 10,10, line to 90,90
2359 paperproto.path = function (pathString) {
2360 pathString && !R.is(pathString, string) && !R.is(pathString[0], array) && (pathString += E);
2361 var out = R._engine.path(R.format[apply](R, arguments), this);
2362 this.__set__ && this.__set__.push(out);
2369 * Embeds an image into the surface.
2373 - src (string) URI of the source image
2374 - x (number) x coordinate position
2375 - y (number) y coordinate position
2376 - width (number) width of the image
2377 - height (number) height of the image
2378 = (object) Raphaël element object with type “image”
2381 | var c = paper.image("apple.png", 10, 10, 80, 80);
2383 paperproto.image = function (src, x, y, w, h) {
2384 var out = R._engine.image(this, src || "about:blank", x || 0, y || 0, w || 0, h || 0);
2385 this.__set__ && this.__set__.push(out);
2392 * Draws a text string. If you need line breaks, put “\n” in the string.
2396 - x (number) x coordinate position
2397 - y (number) y coordinate position
2398 - text (string) The text string to draw
2399 = (object) Raphaël element object with type “text”
2402 | var t = paper.text(50, 50, "Raphaël\nkicks\nbutt!");
2404 paperproto.text = function (x, y, text) {
2405 var out = R._engine.text(this, x || 0, y || 0, Str(text));
2406 this.__set__ && this.__set__.push(out);
2413 * Creates array-like object to keep and operate several elements at once.
2414 * Warning: it doesn’t create any elements for itself in the page, it just groups existing elements.
2415 * Sets act as pseudo elements — all methods available to an element can be used on a set.
2416 = (object) array-like object that represents set of elements
2419 | var st = paper.set();
2421 | paper.circle(10, 10, 5),
2422 | paper.circle(30, 10, 5)
2424 | st.attr({fill: "red"}); // changes the fill of both circles
2426 paperproto.set = function (itemsArray) {
2427 !R.is(itemsArray, "array") && (itemsArray = Array.prototype.splice.call(arguments, 0, arguments.length));
2428 var out = new Set(itemsArray);
2429 this.__set__ && this.__set__.push(out);
2436 * Creates @Paper.set. All elements that will be created after calling this method and before calling
2437 * @Paper.setFinish will be added to the set.
2441 | paper.circle(10, 10, 5),
2442 | paper.circle(30, 10, 5)
2443 | var st = paper.setFinish();
2444 | st.attr({fill: "red"}); // changes the fill of both circles
2446 paperproto.setStart = function (set) {
2447 this.__set__ = set || this.set();
2453 * See @Paper.setStart. This method finishes catching and returns resulting set.
2457 paperproto.setFinish = function (set) {
2458 var out = this.__set__;
2459 delete this.__set__;
2466 * If you need to change dimensions of the canvas call this method
2470 - width (number) new width of the canvas
2471 - height (number) new height of the canvas
2473 | var st = paper.set();
2475 | paper.circle(10, 10, 5),
2476 | paper.circle(30, 10, 5)
2478 | st.attr({fill: "red"});
2480 paperproto.setSize = R._engine.setSize;
2485 * Sets the view box of the paper. Practically it gives you ability to zoom and pan whole paper surface by
2486 * specifying new boundaries.
2491 - x (number) new x position, default is `0`
2492 - y (number) new y position, default is `0`
2493 - w (number) new width of the canvas
2494 - h (number) new height of the canvas
2495 - fit (boolean) `true` if you want graphics to fit into new boundary box
2497 paperproto.setViewBox = R._engine.setViewBox;
2502 * Points to the topmost element on the paper
2508 * Points to the bottom element on the paper
2510 paperproto.top = paperproto.bottom = null;
2515 * Points to the @Raphael object/function
2517 paperproto.raphael = R;
2518 var getOffset = function (elem) {
2519 var box = elem.getBoundingClientRect(),
2520 doc = elem.ownerDocument,
2522 docElem = doc.documentElement,
2523 clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0,
2524 top = box.top + (g.win.pageYOffset || docElem.scrollTop || body.scrollTop ) - clientTop,
2525 left = box.left + (g.win.pageXOffset || docElem.scrollLeft || body.scrollLeft) - clientLeft;
2532 * Paper.getElementByPoint
2535 * Returns you topmost element under given point.
2537 = (object) Raphaël element object
2540 - x (number) x coordinate from the top left corner of the window
2541 - y (number) y coordinate from the top left corner of the window
2543 | paper.getElementByPoint(mouseX, mouseY).attr({stroke: "#f00"});
2545 paperproto.getElementByPoint = function (x, y) {
2548 target = g.doc.elementFromPoint(x, y);
2549 if (g.win.opera && target.tagName == "svg") {
2550 var so = getOffset(svg),
2551 sr = svg.createSVGRect();
2554 sr.width = sr.height = 1;
2555 var hits = svg.getIntersectionList(sr, null);
2557 target = hits[hits.length - 1];
2563 while (target.parentNode && target != svg.parentNode && !target.raphael) {
2564 target = target.parentNode;
2566 target == paper.canvas.parentNode && (target = svg);
2567 target = target && target.raphael ? paper.getById(target.raphaelid) : null;
2574 * Returns you element by its internal ID.
2579 = (object) Raphaël element object
2581 paperproto.getById = function (id) {
2582 var bot = this.bottom;
2595 * Executes given function for each element on the paper
2597 * If callback function returns `false` it will stop loop running.
2601 - callback (function) function to run
2602 - thisArg (object) context object for the callback
2603 = (object) Paper object
2605 paperproto.forEach = function (callback, thisArg) {
2606 var bot = this.bottom;
2608 if (callback.call(thisArg, bot) === false) {
2616 return this.x + S + this.y;
2618 function x_y_w_h() {
2619 return this.x + S + this.y + S + this.width + " \xd7 " + this.height;
2625 * Return bounding box for a given element
2629 - isWithoutTransform (boolean) flag, `true` if you want to have bounding box before transformations. Default is `false`.
2630 = (object) Bounding box object:
2632 o x: (number) top left corner x
2633 o y: (number) top left corner y
2634 o width: (number) width
2635 o height: (number) height
2638 elproto.getBBox = function (isWithoutTransform) {
2643 if (isWithoutTransform) {
2644 if (_.dirty || !_.bboxwt) {
2645 this.realPath = getPath[this.type](this);
2646 _.bboxwt = pathDimensions(this.realPath);
2647 _.bboxwt.toString = x_y_w_h;
2652 if (_.dirty || _.dirtyT || !_.bbox) {
2653 if (_.dirty || !this.realPath) {
2655 this.realPath = getPath[this.type](this);
2657 _.bbox = pathDimensions(mapPath(this.realPath, this.matrix));
2658 _.bbox.toString = x_y_w_h;
2659 _.dirty = _.dirtyT = 0;
2667 = (object) clone of a given element
2670 elproto.clone = function () {
2674 return this.paper[this.type]().attr(this.attr());
2680 * Return set of elements that create glow-like effect around given element. See @Paper.set.
2682 * Note: Glow is not connected to the element. If you change element attributes it won’t adjust itself.
2686 - glow (object) #optional parameters object with all properties optional:
2688 o width (number) size of the glow, default is `10`
2689 o fill (boolean) will it be filled, default is `false`
2690 o opacity: opacity, default is `0.5`
2691 o offsetx: horizontal offset, default is `0`
2692 o offsety: vertical offset, default is `0`
2693 o color: glow colour, default is `black`
2695 = (object) @Paper.set of elements that represents glow
2697 elproto.glow = function (glow) {
2698 if (this.type == "text") {
2703 width: (glow.width || 10) + (+this.attr("stroke-width") || 1),
2704 fill: glow.fill || false,
2705 opacity: glow.opacity || .5,
2706 offsetx: glow.offsetx || 0,
2707 offsety: glow.offsety || 0,
2708 color: glow.color || "#000"
2713 path = this.realPath || getPath[this.type](this);
2714 path = this.matrix ? mapPath(path, this.matrix) : path;
2715 for (var i = 1; i < c + 1; i++) {
2716 out.push(r.path(path).attr({
2718 fill: s.fill ? s.color : "none",
2719 "stroke-linejoin": "round",
2720 "stroke-linecap": "round",
2721 "stroke-width": +(s.width / c * i).toFixed(3),
2722 opacity: +(s.opacity / c).toFixed(3)
2725 return out.insertBefore(this).translate(s.offsetx, s.offsety);
2727 var curveslengths = {},
2728 getPointAtSegmentLength = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length) {
2731 name = [p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y].join(),
2732 cache = curveslengths[name],
2734 !cache && (curveslengths[name] = cache = {data: []});
2735 cache.timer && clearTimeout(cache.timer);
2736 cache.timer = setTimeout(function () {delete curveslengths[name];}, 2e3);
2737 if (length != null && !cache.precision) {
2738 var total = getPointAtSegmentLength(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y);
2739 cache.precision = ~~total * 10;
2742 precision = cache.precision || precision;
2743 for (var i = 0; i < precision + 1; i++) {
2744 if (cache.data[i * precision]) {
2745 dot = cache.data[i * precision];
2747 dot = R.findDotsAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, i / precision);
2748 cache.data[i * precision] = dot;
2750 i && (len += pow(pow(old.x - dot.x, 2) + pow(old.y - dot.y, 2), .5));
2751 if (length != null && len >= length) {
2756 if (length == null) {
2760 getLengthFactory = function (istotal, subpath) {
2761 return function (path, length, onlystart) {
2762 path = path2curve(path);
2763 var x, y, p, l, sp = "", subpaths = {}, point,
2765 for (var i = 0, ii = path.length; i < ii; i++) {
2771 l = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6]);
2772 if (len + l > length) {
2773 if (subpath && !subpaths.start) {
2774 point = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6], length - len);
2775 sp += ["C" + point.start.x, point.start.y, point.m.x, point.m.y, point.x, point.y];
2776 if (onlystart) {return sp;}
2777 subpaths.start = sp;
2778 sp = ["M" + point.x, point.y + "C" + point.n.x, point.n.y, point.end.x, point.end.y, p[5], p[6]].join();
2784 if (!istotal && !subpath) {
2785 point = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6], length - len);
2786 return {x: point.x, y: point.y, alpha: point.alpha};
2793 sp += p.shift() + p;
2796 point = istotal ? len : subpath ? subpaths : R.findDotsAtSegment(x, y, p[1], p[2], p[3], p[4], p[5], p[6], 1);
2797 point.alpha && (point = {x: point.x, y: point.y, alpha: point.alpha});
2801 var getTotalLength = getLengthFactory(1),
2802 getPointAtLength = getLengthFactory(),
2803 getSubpathsAtLength = getLengthFactory(0, 1);
2805 * Raphael.getTotalLength
2808 * Returns length of the given path in pixels.
2812 - path (string) SVG path string.
2816 R.getTotalLength = getTotalLength;
2818 * Raphael.getPointAtLength
2821 * Return coordinates of the point located at the given length on the given path.
2825 - path (string) SVG path string
2828 = (object) representation of the point:
2830 o x: (number) x coordinate
2831 o y: (number) y coordinate
2832 o alpha: (number) angle of derivative
2835 R.getPointAtLength = getPointAtLength;
2837 * Raphael.getSubpath
2840 * Return subpath of a given path from given length to given length.
2844 - path (string) SVG path string
2845 - from (number) position of the start of the segment
2846 - to (number) position of the end of the segment
2848 = (string) pathstring for the segment
2850 R.getSubpath = function (path, from, to) {
2851 if (abs(this.getTotalLength(path) - to) < 1e-6) {
2852 return getSubpathsAtLength(path, from).end;
2854 var a = getSubpathsAtLength(path, to, 1);
2855 return from ? getSubpathsAtLength(a, from).end : a;
2858 * Element.getTotalLength
2861 * Returns length of the path in pixels. Only works for element of “path” type.
2864 elproto.getTotalLength = function () {
2865 if (this.type != "path") {return;}
2866 if (this.node.getTotalLength) {
2867 return this.node.getTotalLength();
2869 return getTotalLength(this.attrs.path);
2872 * Element.getPointAtLength
2875 * Return coordinates of the point located at the given length on the given path. Only works for element of “path” type.
2881 = (object) representation of the point:
2883 o x: (number) x coordinate
2884 o y: (number) y coordinate
2885 o alpha: (number) angle of derivative
2888 elproto.getPointAtLength = function (length) {
2889 if (this.type != "path") {return;}
2890 return getPointAtLength(this.attrs.path, length);
2893 * Element.getSubpath
2896 * Return subpath of a given element from given length to given length. Only works for element of “path” type.
2900 - from (number) position of the start of the segment
2901 - to (number) position of the end of the segment
2903 = (string) pathstring for the segment
2905 elproto.getSubpath = function (from, to) {
2906 if (this.type != "path") {return;}
2907 return R.getSubpath(this.attrs.path, from, to);
2910 * Raphael.easing_formulas
2913 * Object that contains easing formulas for animation. You could extend it with your own. By default it has following list of easing:
2916 # <li>“<” or “easeIn” or “ease-in”</li>
2917 # <li>“>” or “easeOut” or “ease-out”</li>
2918 # <li>“<>” or “easeInOut” or “ease-in-out”</li>
2919 # <li>“backIn” or “back-in”</li>
2920 # <li>“backOut” or “back-out”</li>
2921 # <li>“elastic”</li>
2924 # <p>See also <a href="http://raphaeljs.com/easing.html">Easing demo</a>.</p>
2926 var ef = R.easing_formulas = {
2927 linear: function (n) {
2936 "<>": function (n) {
2937 var q = .48 - n / 1.04,
2938 Q = math.sqrt(.1734 + q * q),
2940 X = pow(abs(x), 1 / 3) * (x < 0 ? -1 : 1),
2942 Y = pow(abs(y), 1 / 3) * (y < 0 ? -1 : 1),
2944 return (1 - t) * 3 * t * t + t * t * t;
2946 backIn: function (n) {
2948 return n * n * ((s + 1) * n - s);
2950 backOut: function (n) {
2953 return n * n * ((s + 1) * n + s) + 1;
2955 elastic: function (n) {
2959 return pow(2, -10 * n) * math.sin((n - .075) * (2 * PI) / .3) + 1;
2961 bounce: function (n) {
2970 l = s * n * n + .75;
2972 if (n < (2.5 / p)) {
2974 l = s * n * n + .9375;
2977 l = s * n * n + .984375;
2984 ef.easeIn = ef["ease-in"] = ef["<"];
2985 ef.easeOut = ef["ease-out"] = ef[">"];
2986 ef.easeInOut = ef["ease-in-out"] = ef["<>"];
2987 ef["back-in"] = ef.backIn;
2988 ef["back-out"] = ef.backOut;
2990 var animationElements = [],
2991 requestAnimFrame = window.requestAnimationFrame ||
2992 window.webkitRequestAnimationFrame ||
2993 window.mozRequestAnimationFrame ||
2994 window.oRequestAnimationFrame ||
2995 window.msRequestAnimationFrame ||
2996 function (callback) {
2997 setTimeout(callback, 16);
2999 animation = function () {
3000 var Now = +new Date,
3002 for (; l < animationElements.length; l++) {
3003 var e = animationElements[l];
3004 if (e.el.removed || e.paused) {
3007 var time = Now - e.start,
3018 time = (e.initstatus * e.anim.top - e.prev) / (e.percent - e.prev) * ms;
3019 e.status = e.initstatus;
3020 delete e.initstatus;
3021 e.stop && animationElements.splice(l--, 1);
3023 e.status = (e.prev + (e.percent - e.prev) * (time / ms)) / e.anim.top;
3029 var pos = easing(time / ms);
3030 for (var attr in from) if (from[has](attr)) {
3031 switch (availableAnimAttrs[attr]) {
3033 now = +from[attr] + pos * ms * diff[attr];
3037 upto255(round(from[attr].r + pos * ms * diff[attr].r)),
3038 upto255(round(from[attr].g + pos * ms * diff[attr].g)),
3039 upto255(round(from[attr].b + pos * ms * diff[attr].b))
3044 for (var i = 0, ii = from[attr].length; i < ii; i++) {
3045 now[i] = [from[attr][i][0]];
3046 for (var j = 1, jj = from[attr][i].length; j < jj; j++) {
3047 now[i][j] = +from[attr][i][j] + pos * ms * diff[attr][i][j];
3049 now[i] = now[i].join(S);
3054 if (diff[attr].real) {
3056 for (i = 0, ii = from[attr].length; i < ii; i++) {
3057 now[i] = [from[attr][i][0]];
3058 for (j = 1, jj = from[attr][i].length; j < jj; j++) {
3059 now[i][j] = from[attr][i][j] + pos * ms * diff[attr][i][j];
3063 var get = function (i) {
3064 return +from[attr][i] + pos * ms * diff[attr][i];
3066 // now = [["r", get(2), 0, 0], ["t", get(3), get(4)], ["s", get(0), get(1), 0, 0]];
3067 now = [["m", get(0), get(1), get(2), get(3), get(4), get(5)]];
3071 if (attr == "clip-rect") {
3075 now[i] = +from[attr][i] + pos * ms * diff[attr][i];
3080 var from2 = [].concat(from[attr]);
3082 i = that.paper.customAttributes[attr].length;
3084 now[i] = +from2[i] + pos * ms * diff[attr][i];
3091 (function (id, that, anim) {
3092 setTimeout(function () {
3093 eve("anim.frame." + id, that, anim);
3095 })(that.id, that, e.anim);
3097 (function(f, el, a) {
3098 setTimeout(function() {
3099 eve("anim.frame." + el.id, el, a);
3100 eve("anim.finish." + el.id, el, a);
3101 R.is(f, "function") && f.call(el);
3103 })(e.callback, that, e.anim);
3105 animationElements.splice(l--, 1);
3106 if (e.repeat > 1 && !e.next) {
3107 runAnimation(e.anim, e.el, e.anim.percents[0], null, e.totalOrigin, e.repeat - 1);
3109 if (e.next && !e.stop) {
3110 runAnimation(e.anim, e.el, e.next, null, e.totalOrigin, e.repeat);
3114 R.svg && that && that.paper && that.paper.safari();
3115 animationElements.length && requestAnimFrame(animation);
3117 upto255 = function (color) {
3118 return color > 255 ? 255 : color < 0 ? 0 : color;
3121 * Element.animateWith
3124 * Acts similar to @Element.animate, but ensure that given animation runs in sync with another given element.
3128 - params (object) final attributes for the element, see also @Element.attr
3129 - ms (number) number of milliseconds for animation to run
3130 - easing (string) #optional easing type. Accept on of @Raphael.easing_formulas or CSS format: `cubic‐bezier(XX, XX, XX, XX)`
3131 - callback (function) #optional callback function. Will be called at the end of animation.
3133 - animation (object) animation object, see @Raphael.animation
3135 = (object) original element
3137 elproto.animateWith = function (element, params, ms, easing, callback) {
3138 this.animate(params, ms, easing, callback);
3140 for (var i = 0, ii = animationElements.length; i < ii; i++) {
3141 el = animationElements[i];
3142 if (el.el.id == element.id) {
3143 start = el.timestamp;
3144 } else if (el.el.id == this.id) {
3148 return this.animate(params, ms, easing, callback);
3150 function CubicBezierAtTime(t, p1x, p1y, p2x, p2y, duration) {
3152 bx = 3 * (p2x - p1x) - cx,
3155 by = 3 * (p2y - p1y) - cy,
3157 function sampleCurveX(t) {
3158 return ((ax * t + bx) * t + cx) * t;
3160 function solve(x, epsilon) {
3161 var t = solveCurveX(x, epsilon);
3162 return ((ay * t + by) * t + cy) * t;
3164 function solveCurveX(x, epsilon) {
3165 var t0, t1, t2, x2, d2, i;
3166 for(t2 = x, i = 0; i < 8; i++) {
3167 x2 = sampleCurveX(t2) - x;
3168 if (abs(x2) < epsilon) {
3171 d2 = (3 * ax * t2 + 2 * bx) * t2 + cx;
3172 if (abs(d2) < 1e-6) {
3187 x2 = sampleCurveX(t2);
3188 if (abs(x2 - x) < epsilon) {
3196 t2 = (t1 - t0) / 2 + t0;
3200 return solve(t, 1 / (200 * duration));
3202 elproto.onAnimation = function (f) {
3203 f ? eve.on("anim.frame." + this.id, f) : eve.unbind("anim.frame." + this.id);
3206 function Animation(anim, ms) {
3212 for (var attr in this.anim) if (this.anim[has](attr)) {
3213 percents.push(+attr);
3215 percents.sort(sortByNumber);
3217 this.top = percents[percents.length - 1];
3218 this.percents = percents;
3224 * Creates a copy of existing animation object with given delay.
3228 - delay (number) number of ms to pass between animation start and actual animation
3230 = (object) new altered Animation object
3232 Animation.prototype.delay = function (delay) {
3233 var a = new Animation(this.anim, this.ms);
3234 a.times = this.times;
3235 a.del = +delay || 0;
3242 * Creates a copy of existing animation object with given repetition.
3246 - repeat (number) number iterations of animation. For infinite animation pass `Infinity`
3248 = (object) new altered Animation object
3250 Animation.prototype.repeat = function (times) {
3251 var a = new Animation(this.anim, this.ms);
3253 a.times = math.floor(mmax(times, 0)) || 1;
3256 function runAnimation(anim, element, percent, status, totalOrigin, times) {
3257 percent = toFloat(percent);
3270 for (i = 0, ii = animationElements.length; i < ii; i++) {
3271 var e = animationElements[i];
3272 if (e.el.id == element.id && e.anim == anim) {
3273 if (e.percent != percent) {
3274 animationElements.splice(i, 1);
3279 element.attr(e.totalOrigin);
3284 status = +to; // NaN
3286 for (var i = 0, ii = anim.percents.length; i < ii; i++) {
3287 if (anim.percents[i] == percent || anim.percents[i] > status * anim.top) {
3288 percent = anim.percents[i];
3289 prev = anim.percents[i - 1] || 0;
3290 ms = ms / anim.top * (percent - prev);
3291 next = anim.percents[i + 1];
3292 params = anim.anim[percent];
3294 } else if (status) {
3295 element.attr(anim.anim[anim.percents[i]]);
3302 for (attr in params) if (params[has](attr)) {
3303 if (availableAnimAttrs[has](attr) || element.paper.customAttributes[has](attr)) {
3304 from[attr] = element.attr(attr);
3305 (from[attr] == null) && (from[attr] = availableAttrs[attr]);
3306 to[attr] = params[attr];
3307 switch (availableAnimAttrs[attr]) {
3309 diff[attr] = (to[attr] - from[attr]) / ms;
3312 from[attr] = R.getRGB(from[attr]);
3313 var toColour = R.getRGB(to[attr]);
3315 r: (toColour.r - from[attr].r) / ms,
3316 g: (toColour.g - from[attr].g) / ms,
3317 b: (toColour.b - from[attr].b) / ms
3321 var pathes = path2curve(from[attr], to[attr]),
3323 from[attr] = pathes[0];
3325 for (i = 0, ii = from[attr].length; i < ii; i++) {
3326 diff[attr][i] = [0];
3327 for (var j = 1, jj = from[attr][i].length; j < jj; j++) {
3328 diff[attr][i][j] = (toPath[i][j] - from[attr][i][j]) / ms;
3334 eq = equaliseTransform(_[attr], to[attr]);
3336 from[attr] = eq.from;
3339 diff[attr].real = true;
3340 for (i = 0, ii = from[attr].length; i < ii; i++) {
3341 diff[attr][i] = [from[attr][i][0]];
3342 for (j = 1, jj = from[attr][i].length; j < jj; j++) {
3343 diff[attr][i][j] = (to[attr][i][j] - from[attr][i][j]) / ms;
3347 var m = (element.matrix || new Matrix),
3349 _: {transform: _.transform},
3350 getBBox: function () {
3351 return element.getBBox(1);
3362 extractTransform(to2, to[attr]);
3363 to[attr] = to2._.transform;
3365 (to2.matrix.a - m.a) / ms,
3366 (to2.matrix.b - m.b) / ms,
3367 (to2.matrix.c - m.c) / ms,
3368 (to2.matrix.d - m.d) / ms,
3369 (to2.matrix.e - m.e) / ms,
3370 (to2.matrix.e - m.f) / ms
3372 // from[attr] = [_.sx, _.sy, _.deg, _.dx, _.dy];
3373 // var to2 = {_:{}, getBBox: function () { return element.getBBox(); }};
3374 // extractTransform(to2, to[attr]);
3376 // (to2._.sx - _.sx) / ms,
3377 // (to2._.sy - _.sy) / ms,
3378 // (to2._.deg - _.deg) / ms,
3379 // (to2._.dx - _.dx) / ms,
3380 // (to2._.dy - _.dy) / ms
3385 var values = Str(params[attr]).split(separator),
3386 from2 = Str(from[attr]).split(separator);
3387 if (attr == "clip-rect") {
3392 diff[attr][i] = (values[i] - from[attr][i]) / ms;
3398 values = [].concat(params[attr]);
3399 from2 = [].concat(from[attr]);
3401 i = element.paper.customAttributes[attr].length;
3403 diff[attr][i] = ((values[i] || 0) - (from2[i] || 0)) / ms;
3409 var easing = params.easing,
3410 easyeasy = R.easing_formulas[easing];
3412 easyeasy = Str(easing).match(bezierrg);
3413 if (easyeasy && easyeasy.length == 5) {
3414 var curve = easyeasy;
3415 easyeasy = function (t) {
3416 return CubicBezierAtTime(t, +curve[1], +curve[2], +curve[3], +curve[4], ms);
3422 timestamp = params.start || anim.start || +new Date;
3426 timestamp: timestamp,
3427 start: timestamp + (anim.del || 0),
3429 initstatus: status || 0,
3437 callback: params.callback,
3440 repeat: times || anim.times,
3441 origin: element.attr(),
3442 totalOrigin: totalOrigin
3444 animationElements.push(e);
3445 if (status && !isInAnim) {
3447 e.start = new Date - ms * status;
3448 if (animationElements.length == 1) {
3452 animationElements.length == 1 && requestAnimFrame(animation);
3454 isInAnim.initstatus = status;
3455 isInAnim.start = new Date - isInAnim.ms * status;
3457 eve("anim.start." + element.id, element, anim);
3463 * Creates an animation object that can be passed to the @Element.animate or @Element.animateWith methods.
3464 * See also @Animation.delay and @Animation.repeat methods.
3468 - params (object) final attributes for the element, see also @Element.attr
3469 - ms (number) number of milliseconds for animation to run
3470 - easing (string) #optional easing type. Accept one of @Raphael.easing_formulas or CSS format: `cubic‐bezier(XX, XX, XX, XX)`
3471 - callback (function) #optional callback function. Will be called at the end of animation.
3473 = (object) @Animation
3475 R.animation = function (params, ms, easing, callback) {
3476 if (R.is(easing, "function") || !easing) {
3477 callback = callback || easing || null;
3480 params = Object(params);
3485 for (attr in params) if (params[has](attr) && toFloat(attr) != attr) {
3487 p[attr] = params[attr];
3490 return new Animation(params, ms);
3492 easing && (p.easing = easing);
3493 callback && (p.callback = callback);
3494 return new Animation({100: p}, ms);
3501 * Creates and starts animation for given element.
3505 - params (object) final attributes for the element, see also @Element.attr
3506 - ms (number) number of milliseconds for animation to run
3507 - easing (string) #optional easing type. Accept one of @Raphael.easing_formulas or CSS format: `cubic‐bezier(XX, XX, XX, XX)`
3508 - callback (function) #optional callback function. Will be called at the end of animation.
3510 - animation (object) animation object, see @Raphael.animation
3512 = (object) original element
3514 elproto.animate = function (params, ms, easing, callback) {
3516 if (element.removed) {
3517 callback && callback.call(element);
3520 var anim = params instanceof Animation ? params : R.animation(params, ms, easing, callback);
3521 runAnimation(anim, element, anim.percents[0], null, element.attr());
3528 * Sets the status of animation of the element in milliseconds. Similar to @Element.status method.
3532 - anim (object) animation object
3533 - value (number) number of milliseconds from the beginning of the animation
3535 = (object) original element if `value` is specified
3536 * Note, that during animation following events are triggered:
3538 * On each animation frame event `anim.frame.<id>`, on start `anim.start.<id>` and on end `anim.finish.<id>`.
3540 elproto.setTime = function (anim, value) {
3541 if (anim && value != null) {
3542 this.status(anim, mmin(value, anim.ms) / anim.ms);
3550 * Gets or sets the status of animation of the element.
3554 - anim (object) #optional animation object
3555 - 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.
3559 = (array) status if `anim` is not specified. Array of objects in format:
3561 o anim: (object) animation object
3562 o status: (number) status
3565 = (object) original element if `value` is specified
3567 elproto.status = function (anim, value) {
3572 if (value != null) {
3573 runAnimation(anim, this, -1, mmin(value, 1));
3576 len = animationElements.length;
3577 for (; i < len; i++) {
3578 e = animationElements[i];
3579 if (e.el.id == this.id && (!anim || e.anim == anim)) {
3583 out.push({anim: e.anim, status: e.status});
3596 * Stops animation of the element with ability to resume it later on.
3600 - anim (object) #optional animation object
3602 = (object) original element
3604 elproto.pause = function (anim) {
3605 for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) {
3606 if (eve("anim.pause." + this.id, this, animationElements[i].anim) !== false) {
3607 animationElements[i].paused = true;
3616 * Resumes animation if it was paused with @Element.pause method.
3620 - anim (object) #optional animation object
3622 = (object) original element
3624 elproto.resume = function (anim) {
3625 for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) {
3626 var e = animationElements[i];
3627 if (eve("anim.resume." + this.id, this, e.anim) !== false) {
3629 this.status(e.anim, e.status);
3638 * Stops animation of the element.
3642 - anim (object) #optional animation object
3644 = (object) original element
3646 elproto.stop = function (anim) {
3647 for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) {
3648 if (eve("anim.stop." + this.id, this, animationElements[i].anim) !== false) {
3649 animationElements.splice(i--, 1);
3654 elproto.toString = function () {
3655 return "Rapha\xebl\u2019s object";
3659 var Set = function (items) {
3664 for (var i = 0, ii = items.length; i < ii; i++) {
3665 if (items[i] && (items[i].constructor == elproto.constructor || items[i].constructor == Set)) {
3666 this[this.items.length] = this.items[this.items.length] = items[i];
3672 setproto = Set.prototype;
3677 * Adds each argument to the current set.
3678 = (object) original element
3680 setproto.push = function () {
3683 for (var i = 0, ii = arguments.length; i < ii; i++) {
3684 item = arguments[i];
3685 if (item && (item.constructor == elproto.constructor || item.constructor == Set)) {
3686 len = this.items.length;
3687 this[len] = this.items[len] = item;
3697 * Removes last element and returns it.
3700 setproto.pop = function () {
3701 this.length && delete this[this.length--];
3702 return this.items.pop();
3708 * Executes given function for each element in the set.
3710 * If function returns `false` it will stop loop running.
3714 - callback (function) function to run
3715 - thisArg (object) context object for the callback
3716 = (object) Set object
3718 setproto.forEach = function (callback, thisArg) {
3719 for (var i = 0, ii = this.items.length; i < ii; i++) {
3720 if (callback.call(thisArg, this.items[i]) === false) {
3726 for (var method in elproto) if (elproto[has](method)) {
3727 setproto[method] = (function (methodname) {
3728 return function () {
3729 var arg = arguments;
3730 return this.forEach(function (el) {
3731 el[methodname][apply](el, arg);
3736 setproto.attr = function (name, value) {
3737 if (name && R.is(name, array) && R.is(name[0], "object")) {
3738 for (var j = 0, jj = name.length; j < jj; j++) {
3739 this.items[j].attr(name[j]);
3742 for (var i = 0, ii = this.items.length; i < ii; i++) {
3743 this.items[i].attr(name, value);
3748 setproto.clear = function () {
3749 while (this.length) {
3753 setproto.animate = function (params, ms, easing, callback) {
3754 (R.is(easing, "function") || !easing) && (callback = easing || null);
3755 var len = this.items.length,
3763 callback && (collector = function () {
3764 !--len && callback.call(set);
3766 easing = R.is(easing, string) ? easing : collector;
3767 var anim = params instanceof Animation ? params : R.animation(params, ms, easing, collector);
3768 item = this.items[--i].animate(anim);
3770 this.items[i] && !this.items[i].removed && this.items[i].animateWith(item, anim);
3774 setproto.insertAfter = function (el) {
3775 var i = this.items.length;
3777 this.items[i].insertAfter(el);
3781 setproto.getBBox = function () {
3786 for (var i = this.items.length; i--;) if (!this.items[i].removed) {
3787 var box = this.items[i].getBBox();
3790 w.push(box.x + box.width);
3791 h.push(box.y + box.height);
3793 x = mmin[apply](0, x);
3794 y = mmin[apply](0, y);
3798 width: mmax[apply](0, w) - x,
3799 height: mmax[apply](0, h) - y
3802 setproto.clone = function (s) {
3804 for (var i = 0, ii = this.items.length; i < ii; i++) {
3805 s.push(this.items[i].clone());
3809 setproto.toString = function () {
3810 return "Rapha\xebl\u2018s set";
3813 R.registerFont = function (font) {
3817 this.fonts = this.fonts || {};
3823 family = font.face["font-family"];
3824 for (var prop in font.face) if (font.face[has](prop)) {
3825 fontcopy.face[prop] = font.face[prop];
3827 if (this.fonts[family]) {
3828 this.fonts[family].push(fontcopy);
3830 this.fonts[family] = [fontcopy];
3833 fontcopy.face["units-per-em"] = toInt(font.face["units-per-em"], 10);
3834 for (var glyph in font.glyphs) if (font.glyphs[has](glyph)) {
3835 var path = font.glyphs[glyph];
3836 fontcopy.glyphs[glyph] = {
3839 d: path.d && "M" + path.d.replace(/[mlcxtrv]/g, function (command) {
3840 return {l: "L", c: "C", x: "z", t: "m", r: "l", v: "c"}[command] || "M";
3844 for (var k in path.k) if (path[has](k)) {
3845 fontcopy.glyphs[glyph].k[k] = path.k[k];
3852 paperproto.getFont = function (family, weight, style, stretch) {
3853 stretch = stretch || "normal";
3854 style = style || "normal";
3855 weight = +weight || {normal: 400, bold: 700, lighter: 300, bolder: 800}[weight] || 400;
3859 var font = R.fonts[family];
3861 var name = new RegExp("(^|\\s)" + family.replace(/[^\w\d\s+!~.:_-]/g, E) + "(\\s|$)", "i");
3862 for (var fontName in R.fonts) if (R.fonts[has](fontName)) {
3863 if (name.test(fontName)) {
3864 font = R.fonts[fontName];
3871 for (var i = 0, ii = font.length; i < ii; i++) {
3873 if (thefont.face["font-weight"] == weight && (thefont.face["font-style"] == style || !thefont.face["font-style"]) && thefont.face["font-stretch"] == stretch) {
3880 paperproto.print = function (x, y, string, font, size, origin, letter_spacing) {
3881 origin = origin || "middle"; // baseline|middle
3882 letter_spacing = mmax(mmin(letter_spacing || 0, 1), -1);
3883 var out = this.set(),
3884 letters = Str(string).split(E),
3888 R.is(font, string) && (font = this.getFont(font));
3890 scale = (size || 16) / font.face["units-per-em"];
3891 var bb = font.face.bbox.split(separator),
3893 height = +bb[1] + (origin == "baseline" ? bb[3] - bb[1] + (+font.face.descent) : (bb[3] - bb[1]) / 2);
3894 for (var i = 0, ii = letters.length; i < ii; i++) {
3895 var prev = i && font.glyphs[letters[i - 1]] || {},
3896 curr = font.glyphs[letters[i]];
3897 shift += i ? (prev.w || font.w) + (prev.k && prev.k[letters[i]] || 0) + (font.w * letter_spacing) : 0;
3898 curr && curr.d && out.push(this.path(curr.d).attr({fill: "#000", stroke: "none", transform: [["t", shift, 0]]}));
3900 out.scale(scale, scale, top, height).translate(x - top, y - height);
3905 R.format = function (token, params) {
3906 var args = R.is(params, array) ? [0][concat](params) : arguments;
3907 token && R.is(token, string) && args.length - 1 && (token = token.replace(formatrg, function (str, i) {
3908 return args[++i] == null ? E : args[i];
3912 R.ninja = function () {
3913 oldRaphael.was ? (g.win.Raphael = oldRaphael.is) : delete Raphael;
3918 [ property (object) ]
3920 * You can add your own method to elements. This is usefull when you want to hack default functionality or
3921 * want to wrap some common transformation or attributes in one method. In difference to canvas methods,
3922 * you can redefine element method at any time. Expending element methods wouldn’t affect set.
3924 | Raphael.el.red = function () {
3925 | this.attr({fill: "#f00"});
3928 | paper.circle(100, 100, 20).red();
3931 // Firefox <3.6 fix: http://webreflection.blogspot.com/2009/11/195-chars-to-help-lazy-loading.html
3932 (function (doc, loaded, f) {
3933 if (doc.readyState == null && doc.addEventListener){
3934 doc.addEventListener(loaded, f = function () {
3935 doc.removeEventListener(loaded, f, false);
3936 doc.readyState = "complete";
3938 doc.readyState = "loading";
3940 function isLoaded() {
3941 (/in/).test(doc.readyState) ? setTimeout(isLoaded, 9) : R.eve("DOMload");
3944 })(document, "DOMContentLoaded");
3946 oldRaphael.was ? (g.win.Raphael = R) : (Raphael = R);
3949 * Eve 0.2.3 - JavaScript Events Library
3951 * Copyright (c) 2010 Dmitry Baranovskiy (http://dmitry.baranovskiy.com/)
3952 * Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) license.
3955 var eve = R.eve = (function () {
3956 var version = "0.2.3",
3957 has = "hasOwnProperty",
3958 separator = /[\.\/]/,
3960 fun = function () {},
3961 numsort = function (a, b) {
3970 * Fires event with given `name`, given scope and other parameters.
3974 - name (string) name of the event, dot (`.`) or slash (`/`) separated
3975 - scope (object) context for the event handlers
3976 - varargs (...) the rest of arguments will be sent to event handlers
3978 = (array) array of errors, if any. Each element of the array is in format:
3980 o error (string) error message
3981 o func (function) handler that caused error
3984 eve = function (name, scope) {
3986 args = Array.prototype.slice.call(arguments, 2),
3987 listeners = eve.listeners(name),
3994 current_event = name;
3995 for (var i = 0, ii = listeners.length; i < ii; i++) if ("zIndex" in listeners[i]) {
3996 indexed.push(listeners[i].zIndex);
3997 if (listeners[i].zIndex < 0) {
3998 queue[listeners[i].zIndex] = listeners[i];
4001 indexed.sort(numsort);
4002 while (indexed[z] < 0) {
4003 l = queue[indexed[z++]];
4004 if (l.apply(scope, args) === f) {
4008 for (i = 0; i < ii; i++) {
4010 if ("zIndex" in l) {
4011 if (l.zIndex == indexed[z]) {
4012 if (l.apply(scope, args) === f) {
4017 l = queue[indexed[z]];
4019 if (l.apply(scope, args) === f) {
4025 queue[l.zIndex] = l;
4028 if (l.apply(scope, args) === f) {
4038 * Internal method which gives you array of all event handlers that will be triggered by the given `name`.
4042 - name (string) name of the event, dot (`.`) or slash (`/`) separated
4044 = (array) array of event handlers
4046 eve.listeners = function (name) {
4047 var names = name.split(separator),
4059 for (i = 0, ii = names.length; i < ii; i++) {
4061 for (j = 0, jj = es.length; j < jj; j++) {
4063 items = [e[names[i]], e[wildcard]];
4069 out = out.concat(item.f || []);
4082 * Binds given event handler with a given name. You can use wildcards “`*`” for the names:
4083 | eve.on("*.under.*", f);
4084 | eve("mouse.under.floor"); // triggers f
4085 * Use @eve to trigger the listener.
4089 - name (string) name of the event, dot (`.`) or slash (`/`) separated, with optional wildcards
4090 - f (function) event handler function
4092 = (function) returned function accept one number parameter that represents z-index of the handler. It is optional feature and only used when you need to ensure that some subset of handlers will be invoked in a given order, despite of the order of assignment.
4094 | eve.on("mouse", eat)(2);
4095 | eve.on("mouse", scream);
4096 | eve.on("mouse", catch)(1);
4097 * This will ensure that `catch` function will be called before `eat`.
4098 * If you want to put you hadler before not indexed handlers specify negative value.
4099 * Note: I assume most of the time you don’t need to worry about z-index, but it’s nice to have this feature “just in case”.
4101 eve.on = function (name, f) {
4102 var names = name.split(separator),
4104 for (var i = 0, ii = names.length; i < ii; i++) {
4106 !e[names[i]] && (e[names[i]] = {n: {}});
4110 for (i = 0, ii = e.f.length; i < ii; i++) if (e.f[i] == f) {
4114 return function (zIndex) {
4115 if (+zIndex == +zIndex) {
4124 * Could be used inside event handler to figure out actual name of the event.
4128 - subname (string) #optional subname of the event
4130 = (string) name of the event, if `subname` is not specified
4132 = (boolean) `true`, if current event’s name contains `subname`
4134 eve.nt = function (subname) {
4136 return new RegExp("(?:\\.|\\/|^)" + subname + "(?:\\.|\\/|$)").test(current_event);
4138 return current_event;
4144 * Removes given function from the list of event listeners assigned to given name.
4148 - name (string) name of the event, dot (`.`) or slash (`/`) separated, with optional wildcards
4149 - f (function) event handler function
4151 eve.unbind = function (name, f) {
4152 var names = name.split(separator),
4157 for (var i = 0, ii = names.length; i < ii; i++) {
4158 for (var j = 0; j < cur.length; j += splice.length - 2) {
4161 if (names[i] != wildcard) {
4163 splice.push(e[names[i]]);
4166 for (key in e) if (e[has](key)) {
4167 splice.push(e[key]);
4170 cur.splice.apply(cur, splice);
4173 for (i = 0, ii = cur.length; i < ii; i++) {
4178 for (i = 0, ii = e.f.length; i < ii; i++) if (e.f[i] == f) {
4182 !e.f.length && delete e.f;
4184 for (key in e.n) if (e.n[has](key) && e.n[key].f) {
4185 var funcs = e.n[key].f;
4186 for (i = 0, ii = funcs.length; i < ii; i++) if (funcs[i] == f) {
4190 !funcs.length && delete e.n[key].f;
4194 for (key in e.n) if (e.n[has](key) && e.n[key].f) {
4204 [ property (string) ]
4206 * Current version of the library.
4208 eve.version = version;
4209 eve.toString = function () {
4210 return "You are running Eve " + version;
4217 eve.on("DOMload", function () {
4222 // ┌─────────────────────────────────────────────────────────────────────┐ \\
4223 // │ Raphaël 2 - JavaScript Vector Library │ \\
4224 // ├─────────────────────────────────────────────────────────────────────┤ \\
4225 // │ SVG Module │ \\
4226 // ├─────────────────────────────────────────────────────────────────────┤ \\
4227 // │ Copyright (c) 2008-2011 Dmitry Baranovskiy (http://raphaeljs.com) │ \\
4228 // │ Copyright (c) 2008-2011 Sencha Labs (http://sencha.com) │ \\
4229 // │ Licensed under the MIT (http://raphaeljs.com/license.html) license. │ \\
4230 // └─────────────────────────────────────────────────────────────────────┘ \\
4231 window.Raphael.svg && function (R) {
4232 var has = "hasOwnProperty",
4234 toFloat = parseFloat,
4240 separator = /[, ]+/,
4244 var xlink = "http://www.w3.org/1999/xlink",
4246 block: "M5,0 0,2.5 5,5z",
4247 classic: "M5,0 0,2.5 5,5 3.5,3 3.5,2z",
4248 diamond: "M2.5,0 5,2.5 2.5,5 0,2.5z",
4249 open: "M6,1 1,3.5 6,6",
4250 oval: "M2.5,0A2.5,2.5,0,0,1,2.5,5 2.5,2.5,0,0,1,2.5,0z"
4253 R.toString = function () {
4254 return "Your browser supports SVG.\nYou are running Rapha\xebl " + this.version;
4256 var $ = function (el, attr) {
4258 if (typeof el == "string") {
4261 for (var key in attr) if (attr[has](key)) {
4262 if (key.substring(0, 6) == "xlink:") {
4263 el.setAttributeNS(xlink, key.substring(6), Str(attr[key]));
4265 el.setAttribute(key, Str(attr[key]));
4269 el = R._g.doc.createElementNS("http://www.w3.org/2000/svg", el);
4270 el.style && (el.style.webkitTapHighlightColor = "rgba(0,0,0,0)");
4275 rgGrad = /^url\(#(.*)\)$/,
4276 removeGradientFill = function (node, paper) {
4277 var oid = node.getAttribute("fill");
4278 oid = oid && oid.match(rgGrad);
4279 if (oid && !--gradients[oid[1]]) {
4280 delete gradients[oid[1]];
4281 paper.defs.removeChild(R._g.doc.getElementById(oid[1]));
4284 addGradientFill = function (element, gradient) {
4285 var type = "linear",
4286 id = element.id + gradient,
4289 SVG = element.paper,
4291 el = R._g.doc.getElementById(id);
4293 gradient = Str(gradient).replace(R._radial_gradient, function (all, _fx, _fy) {
4298 var dir = ((fy > .5) * 2 - 1);
4299 pow(fx - .5, 2) + pow(fy - .5, 2) > .25 &&
4300 (fy = math.sqrt(.25 - pow(fx - .5, 2)) * dir + .5) &&
4302 (fy = fy.toFixed(5) - 1e-5 * dir);
4306 gradient = gradient.split(/\s*\-\s*/);
4307 if (type == "linear") {
4308 var angle = gradient.shift();
4309 angle = -toFloat(angle);
4313 var vector = [0, 0, math.cos(R.rad(angle)), math.sin(R.rad(angle))],
4314 max = 1 / (mmax(abs(vector[2]), abs(vector[3])) || 1);
4317 if (vector[2] < 0) {
4318 vector[0] = -vector[2];
4321 if (vector[3] < 0) {
4322 vector[1] = -vector[3];
4326 var dots = R._parseDots(gradient);
4330 if (element.gradient) {
4331 SVG.defs.removeChild(element.gradient);
4332 delete element.gradient;
4335 id = id.replace(/[\(\)\s,\xb0#]/g, "-");
4336 el = $(type + "Gradient", {id: id});
4337 element.gradient = el;
4338 $(el, type == "radial" ? {
4346 gradientTransform: element.matrix.invert()
4348 SVG.defs.appendChild(el);
4349 for (var i = 0, ii = dots.length; i < ii; i++) {
4350 el.appendChild($("stop", {
4351 offset: dots[i].offset ? dots[i].offset : i ? "100%" : "0%",
4352 "stop-color": dots[i].color || "#fff"
4357 fill: "url(#" + id + ")",
4366 updatePosition = function (o) {
4367 var bbox = o.getBBox(1);
4368 $(o.pattern, {patternTransform: o.matrix.invert() + " translate(" + bbox.x + "," + bbox.y + ")"});
4370 addArrow = function (o, value, isEnd) {
4371 if (o.type == "path") {
4372 var values = Str(value).toLowerCase().split("-"),
4374 se = isEnd ? "end" : "start",
4377 stroke = attrs["stroke-width"],
4389 switch (values[i]) {
4398 case "wide": h = 5; break;
4399 case "narrow": h = 2; break;
4400 case "long": w = 5; break;
4401 case "short": w = 2; break;
4404 if (type == "open") {
4409 refX = isEnd ? 4 : 1;
4412 stroke: attrs.stroke
4423 o._.arrows.endPath && markerCounter[o._.arrows.endPath]--;
4424 o._.arrows.endMarker && markerCounter[o._.arrows.endMarker]--;
4426 o._.arrows.startPath && markerCounter[o._.arrows.startPath]--;
4427 o._.arrows.startMarker && markerCounter[o._.arrows.startMarker]--;
4432 if (type != "none") {
4433 var pathId = "raphael-marker-" + type,
4434 markerId = "raphael-marker-" + se + type + w + h;
4435 if (!R._g.doc.getElementById(pathId)) {
4436 p.defs.appendChild($($("path"), {
4437 "stroke-linecap": "round",
4441 markerCounter[pathId] = 1;
4443 markerCounter[pathId]++;
4445 var marker = R._g.doc.getElementById(markerId),
4448 marker = $($("marker"), {
4457 "xlink:href": "#" + pathId,
4458 transform: (isEnd ? " rotate(180 " + w / 2 + " " + h / 2 + ") " : S) + "scale(" + w / t + "," + h / t + ")",
4459 "stroke-width": 1 / ((w / t + h / t) / 2)
4461 marker.appendChild(use);
4462 p.defs.appendChild(marker);
4463 markerCounter[markerId] = 1;
4465 markerCounter[markerId]++;
4466 use = marker.getElementsByTagName("use")[0];
4469 var delta = dx * (type != "diamond" && type != "oval");
4471 from = o._.arrows.startdx * stroke || 0;
4472 to = R.getTotalLength(attrs.path) - delta * stroke;
4474 from = delta * stroke;
4475 to = R.getTotalLength(attrs.path) - (o._.arrows.enddx * stroke || 0);
4478 attr["marker-" + se] = "url(#" + markerId + ")";
4480 attr.d = Raphael.getSubpath(attrs.path, from, to);
4483 o._.arrows[se + "Path"] = pathId;
4484 o._.arrows[se + "Marker"] = markerId;
4485 o._.arrows[se + "dx"] = delta;
4486 o._.arrows[se + "Type"] = type;
4487 o._.arrows[se + "String"] = value;
4490 from = o._.arrows.startdx * stroke || 0;
4491 to = R.getTotalLength(attrs.path) - from;
4494 to = R.getTotalLength(attrs.path) - (o._.arrows.enddx * stroke || 0);
4496 o._.arrows[se + "Path"] && $(node, {d: Raphael.getSubpath(attrs.path, from, to)});
4497 delete o._.arrows[se + "Path"];
4498 delete o._.arrows[se + "Marker"];
4499 delete o._.arrows[se + "dx"];
4500 delete o._.arrows[se + "Type"];
4501 delete o._.arrows[se + "String"];
4503 for (attr in markerCounter) if (markerCounter[has](attr) && !markerCounter[attr]) {
4504 var item = R._g.doc.getElementById(attr);
4505 item && item.parentNode.removeChild(item);
4509 setFillAndStroke = function (o, params) {
4516 "-..": [3, 1, 1, 1, 1, 1],
4520 "- .": [4, 3, 1, 3],
4521 "--.": [8, 3, 1, 3],
4522 "--..": [8, 3, 1, 3, 1, 3]
4526 addDashes = function (o, value) {
4527 value = dasharray[Str(value).toLowerCase()];
4529 var width = o.attrs["stroke-width"] || "1",
4530 butt = {round: width, square: width, butt: 0}[o.attrs["stroke-linecap"] || params["stroke-linecap"]] || 0,
4534 dashes[i] = value[i] * width + ((i % 2) ? 1 : -1) * butt;
4536 $(node, {"stroke-dasharray": dashes.join(",")});
4539 for (var att in params) {
4540 if (params[has](att)) {
4541 if (!R._availableAttrs[has](att)) {
4544 var value = params[att];
4553 var pn = node.parentNode;
4554 if (pn.tagName.toLowerCase() != "a") {
4556 pn.insertBefore(hl, node);
4557 hl.appendChild(node);
4560 if (att == "target" && value == "blank") {
4561 pn.setAttributeNS(xlink, "show", "new");
4563 pn.setAttributeNS(xlink, att, value);
4567 node.style.cursor = value;
4576 addArrow(o, value, 1);
4579 var rect = Str(value).split(separator);
4580 if (rect.length == 4) {
4581 o.clip && o.clip.parentNode.parentNode.removeChild(o.clip.parentNode);
4582 var el = $("clipPath"),
4584 el.id = R._createUUID();
4592 o.paper.defs.appendChild(el);
4593 $(node, {"clip-path": "url(#" + el.id + ")"});
4597 var clip = R._g.doc.getElementById(node.getAttribute("clip-path").replace(/(^url\(#|\)$)/g, E));
4598 clip && clip.parentNode.removeChild(clip);
4599 $(node, {"clip-path": E});
4604 if (o.type == "path") {
4605 $(node, {d: value ? attrs.path = R._pathToAbsolute(value) : "M0,0"});
4608 "startString" in o._.arrows && addArrow(o, o._.arrows.startString);
4609 "endString" in o._.arrows && addArrow(o, o._.arrows.endString, 1);
4614 node.setAttribute(att, value);
4624 value = -attrs.x - (attrs.width || 0);
4627 if (att == "rx" && o.type == "rect") {
4631 node.setAttribute(att, value);
4632 o.pattern && updatePosition(o);
4636 node.setAttribute(att, value);
4646 value = -attrs.y - (attrs.height || 0);
4649 if (att == "ry" && o.type == "rect") {
4653 node.setAttribute(att, value);
4654 o.pattern && updatePosition(o);
4658 if (o.type == "rect") {
4659 $(node, {rx: value, ry: value});
4661 node.setAttribute(att, value);
4666 if (o.type == "image") {
4667 node.setAttributeNS(xlink, "href", value);
4670 case "stroke-width":
4671 if (o._.sx != 1 || o._.sy != 1) {
4672 value /= mmax(abs(o._.sx), abs(o._.sy)) || 1;
4674 if (o.paper._vbSize) {
4675 value *= o.paper._vbSize;
4677 node.setAttribute(att, value);
4678 if (attrs["stroke-dasharray"]) {
4679 addDashes(o, attrs["stroke-dasharray"]);
4682 "startString" in o._.arrows && addArrow(o, o._.arrows.startString);
4683 "endString" in o._.arrows && addArrow(o, o._.arrows.endString, 1);
4686 case "stroke-dasharray":
4687 addDashes(o, value);
4690 var isURL = Str(value).match(R._ISURL);
4693 var ig = $("image");
4694 el.id = R._createUUID();
4695 $(el, {x: 0, y: 0, patternUnits: "userSpaceOnUse", height: 1, width: 1});
4696 $(ig, {x: 0, y: 0, "xlink:href": isURL[1]});
4700 R._preload(isURL[1], function () {
4701 var w = this.offsetWidth,
4702 h = this.offsetHeight;
4703 $(el, {width: w, height: h});
4704 $(ig, {width: w, height: h});
4708 o.paper.defs.appendChild(el);
4709 node.style.fill = "url(#" + el.id + ")";
4710 $(node, {fill: "url(#" + el.id + ")"});
4712 o.pattern && updatePosition(o);
4715 var clr = R.getRGB(value);
4717 delete params.gradient;
4718 delete attrs.gradient;
4719 !R.is(attrs.opacity, "undefined") &&
4720 R.is(params.opacity, "undefined") &&
4721 $(node, {opacity: attrs.opacity});
4722 !R.is(attrs["fill-opacity"], "undefined") &&
4723 R.is(params["fill-opacity"], "undefined") &&
4724 $(node, {"fill-opacity": attrs["fill-opacity"]});
4725 } else if ((o.type == "circle" || o.type == "ellipse" || Str(value).charAt() != "r") && addGradientFill(o, value)) {
4726 if ("opacity" in attrs || "fill-opacity" in attrs) {
4727 var gradient = R._g.doc.getElementById(node.getAttribute("fill").replace(/^url\(#|\)$/g, E));
4729 var stops = gradient.getElementsByTagName("stop");
4730 $(stops[stops.length - 1], {"stop-opacity": ("opacity" in attrs ? attrs.opacity : 1) * ("fill-opacity" in attrs ? attrs["fill-opacity"] : 1)});
4733 attrs.gradient = value;
4734 attrs.fill = "none";
4737 clr[has]("opacity") && $(node, {"fill-opacity": clr.opacity > 1 ? clr.opacity / 100 : clr.opacity});
4739 clr = R.getRGB(value);
4740 node.setAttribute(att, clr.hex);
4741 att == "stroke" && clr[has]("opacity") && $(node, {"stroke-opacity": clr.opacity > 1 ? clr.opacity / 100 : clr.opacity});
4742 if (att == "stroke" && o._.arrows) {
4743 "startString" in o._.arrows && addArrow(o, o._.arrows.startString);
4744 "endString" in o._.arrows && addArrow(o, o._.arrows.endString, 1);
4748 (o.type == "circle" || o.type == "ellipse" || Str(value).charAt() != "r") && addGradientFill(o, value);
4751 if (attrs.gradient && !attrs[has]("stroke-opacity")) {
4752 $(node, {"stroke-opacity": value > 1 ? value / 100 : value});
4755 case "fill-opacity":
4756 if (attrs.gradient) {
4757 gradient = R._g.doc.getElementById(node.getAttribute("fill").replace(/^url\(#|\)$/g, E));
4759 stops = gradient.getElementsByTagName("stop");
4760 $(stops[stops.length - 1], {"stop-opacity": value});
4765 att == "font-size" && (value = toInt(value, 10) + "px");
4766 var cssrule = att.replace(/(\-.)/g, function (w) {
4767 return w.substring(1).toUpperCase();
4769 node.style[cssrule] = value;
4771 node.setAttribute(att, value);
4777 tuneText(o, params);
4780 tuneText = function (el, params) {
4781 if (el.type != "text" || !(params[has]("text") || params[has]("font") || params[has]("font-size") || params[has]("x") || params[has]("y"))) {
4786 fontSize = node.firstChild ? toInt(R._g.doc.defaultView.getComputedStyle(node.firstChild, E).getPropertyValue("font-size"), 10) : 10;
4788 if (params[has]("text")) {
4789 a.text = params.text;
4790 while (node.firstChild) {
4791 node.removeChild(node.firstChild);
4793 var texts = Str(params.text).split("\n"),
4796 for (var i = 0, ii = texts.length; i < ii; i++) {
4798 i && $(tspan, {dy: fontSize * leading, x: a.x});
4799 tspan.appendChild(R._g.doc.createTextNode(texts[i]));
4800 node.appendChild(tspan);
4804 tspans = node.getElementsByTagName("tspan");
4805 for (i = 0, ii = tspans.length; i < ii; i++) if (i) {
4806 $(tspans[i], {dy: fontSize * leading, x: a.x});
4808 $(tspans[0], {dy: 0});
4811 $(node, {x: a.x, y: a.y});
4813 var bb = el._getBBox(),
4814 dif = a.y - (bb.y + bb.height / 2);
4815 dif && R.is(dif, "finite") && $(tspans[0], {dy: dif});
4817 Element = function (node, svg) {
4822 [ property (object) ]
4824 * Gives you a reference to the DOM object, so you can assign event handlers or just mess around.
4826 | // draw a circle at coordinate 10,10 with radius of 10
4827 | var c = paper.circle(10, 10, 10);
4828 | c.node.onclick = function () {
4829 | c.attr("fill", "red");
4832 this[0] = this.node = node;
4835 [ property (object) ]
4837 * Internal reference to @Raphael object. In case it is not available.
4839 | Raphael.el.red = function () {
4840 | var hsb = this.paper.raphael.rgb2hsb(this.attr("fill"));
4842 | this.attr({fill: this.paper.raphael.hsb2rgb(hsb).hex});
4845 node.raphael = true;
4848 [ property (number) ]
4850 * Unique id of the element. Especially usesful when you want to listen to events of the element,
4851 * because all events are fired in format `<module>.<action>.<id>`. Also useful for @Paper.getById method.
4854 node.raphaelid = this.id;
4855 this.matrix = R.matrix();
4856 this.realPath = null;
4859 [ property (object) ]
4861 * Internal reference to “paper” where object drawn. Mainly for use in plugins and element extensions.
4863 | Raphael.el.cross = function () {
4864 | this.attr({fill: "red"});
4865 | this.paper.path("M10,10L50,50M50,10L10,50")
4866 | .attr({stroke: "red"});
4870 this.attrs = this.attrs || {};
4880 !svg.bottom && (svg.bottom = this);
4883 [ property (object) ]
4885 * Reference to the previous element in the hierarchy.
4887 this.prev = svg.top;
4888 svg.top && (svg.top.next = this);
4892 [ property (object) ]
4894 * Reference to the next element in the hierarchy.
4900 Element.prototype = elproto;
4901 elproto.constructor = Element;
4903 R._engine.path = function (pathString, SVG) {
4905 SVG.canvas && SVG.canvas.appendChild(el);
4906 var p = new Element(el, SVG);
4908 setFillAndStroke(p, {fill: "none", stroke: "#000", path: pathString});
4915 * Adds rotation by given angle around given point to the list of
4916 * transformations of the element.
4918 - deg (number) angle in degrees
4919 - cx (number) #optional x coordinate of the centre of rotation
4920 - cy (number) #optional y coordinate of the centre of rotation
4921 * If cx & cy aren’t specified centre of the shape is used as a point of rotation.
4924 elproto.rotate = function (deg, cx, cy) {
4928 deg = Str(deg).split(separator);
4929 if (deg.length - 1) {
4930 cx = toFloat(deg[1]);
4931 cy = toFloat(deg[2]);
4933 deg = toFloat(deg[0]);
4934 (cy == null) && (cx = cy);
4935 if (cx == null || cy == null) {
4936 var bbox = this.getBBox(1);
4937 cx = bbox.x + bbox.width / 2;
4938 cy = bbox.y + bbox.height / 2;
4940 this.transform(this._.transform.concat([["r", deg, cx, cy]]));
4947 * Adds scale by given amount relative to given point to the list of
4948 * transformations of the element.
4950 - sx (number) horisontal scale amount
4951 - sy (number) vertical scale amount
4952 - cx (number) #optional x coordinate of the centre of scale
4953 - cy (number) #optional y coordinate of the centre of scale
4954 * If cx & cy aren’t specified centre of the shape is used instead.
4957 elproto.scale = function (sx, sy, cx, cy) {
4961 sx = Str(sx).split(separator);
4962 if (sx.length - 1) {
4963 sy = toFloat(sx[1]);
4964 cx = toFloat(sx[2]);
4965 cy = toFloat(sx[3]);
4967 sx = toFloat(sx[0]);
4968 (sy == null) && (sy = sx);
4969 (cy == null) && (cx = cy);
4970 if (cx == null || cy == null) {
4971 var bbox = this.getBBox(1);
4973 cx = cx == null ? bbox.x + bbox.width / 2 : cx;
4974 cy = cy == null ? bbox.y + bbox.height / 2 : cy;
4975 this.transform(this._.transform.concat([["s", sx, sy, cx, cy]]));
4982 * Adds translation by given amount to the list of transformations of the element.
4984 - dx (number) horisontal shift
4985 - dy (number) vertical shift
4988 elproto.translate = function (dx, dy) {
4992 dx = Str(dx).split(separator);
4993 if (dx.length - 1) {
4994 dy = toFloat(dx[1]);
4996 dx = toFloat(dx[0]) || 0;
4998 this.transform(this._.transform.concat([["t", dx, dy]]));
5005 * Adds transformation to the element which is separate to other attributes,
5006 * i.e. translation doesn’t change `x` or `y` of the rectange. The format
5007 * of transformation string is similar to the path string syntax:
5008 | "t100,100r30,100,100s2,2,100,100r45s1.5"
5009 * Each letter is a command. There are four commands: `t` is for translate, `r` is for rotate, `s` is for
5010 * scale and `m` is for matrix.
5012 * So, the example line above could be read like “translate by 100, 100; rotate 30° around 100, 100; scale twice around 100, 100;
5013 * rotate 45° around centre; scale 1.5 times relative to centre”. As you can see rotate and scale commands have origin
5014 * coordinates as optional parameters, the default is the centre point of the element.
5015 * Matrix accepts six parameters.
5017 | var el = paper.rect(10, 20, 300, 200);
5018 | // translate 100, 100, rotate 45°, translate -100, 0
5019 | el.transform("t100,100r45t-100,0");
5020 | // if you want you can append or prepend transformations
5021 | el.transform("...t50,50");
5022 | el.transform("s2...");
5024 | el.transform("t50,50...t-50-50");
5025 | // to reset transformation call method with empty string
5027 | // to get current value call it without parameters
5028 | console.log(el.transform());
5030 - tstr (string) #optional transformation string
5031 * If tstr isn’t specified
5032 = (string) current transformation string
5036 elproto.transform = function (tstr) {
5041 R._extractTransform(this, tstr);
5043 this.clip && $(this.clip, {transform: this.matrix.invert()});
5044 this.pattern && updatePosition(this);
5045 this.node && $(this.node, {transform: this.matrix});
5047 if (_.sx != 1 || _.sy != 1) {
5048 var sw = this.attrs[has]("stroke-width") ? this.attrs["stroke-width"] : 1;
5049 this.attr({"stroke-width": sw});
5058 * Makes element invisible. See @Element.show.
5061 elproto.hide = function () {
5062 !this.removed && this.paper.safari(this.node.style.display = "none");
5069 * Makes element visible. See @Element.hide.
5072 elproto.show = function () {
5073 !this.removed && this.paper.safari(this.node.style.display = "");
5080 * Removes element form the paper.
5082 elproto.remove = function () {
5086 eve.unbind("*.*." + this.id);
5087 R._tear(this, this.paper);
5088 this.node.parentNode.removeChild(this.node);
5089 for (var i in this) {
5092 this.removed = true;
5094 elproto._getBBox = function () {
5095 if (this.node.style.display == "none") {
5101 bbox = this.node.getBBox();
5103 // Firefox 3.0.x plays badly here
5107 hide && this.hide();
5114 * Sets the attributes of the element.
5116 - attrName (string) attribute’s name
5117 - value (string) value
5119 - params (object) object of name/value pairs
5121 - attrName (string) attribute’s name
5123 - attrNames (array) in this case method returns array of current values for given attribute names
5124 = (object) @Element if attrsName & value or params are passed in.
5125 = (...) value of the attribute if only attrsName is passed in.
5126 = (array) array of values of the attribute if attrsNames is passed in.
5127 = (object) object of attributes if nothing is passed in.
5128 > Possible parameters
5129 # <p>Please refer to the <a href="http://www.w3.org/TR/SVG/" title="The W3C Recommendation for the SVG language describes these properties in detail.">SVG specification</a> for an explanation of these parameters.</p>
5130 o arrow-end (string) arrowhead on the end of the path. The format for string is `<type>[-<width>[-<length>]]`. Possible types: `classic`, `block`, `open`, `oval`, `diamond`, `none`, width: `wide`, `narrow`, `midium`, length: `long`, `short`, `midium`.
5131 o clip-rect (string) comma or space separated values: x, y, width and height
5132 o cursor (string) CSS type of the cursor
5135 o fill (string) colour, gradient or image
5136 o fill-opacity (number)
5138 o font-family (string)
5139 o font-size (number) font size in pixels
5140 o font-weight (string)
5142 o href (string) URL, if specified element behaves as hyperlink
5144 o path (string) SVG path string format
5148 o src (string) image URL, only works for @Element.image element
5149 o stroke (string) stroke colour
5150 o stroke-dasharray (string) [“”, “`-`”, “`.`”, “`-.`”, “`-..`”, “`. `”, “`- `”, “`--`”, “`- .`”, “`--.`”, “`--..`”]
5151 o stroke-linecap (string) [“`butt`”, “`square`”, “`round`”]
5152 o stroke-linejoin (string) [“`bevel`”, “`round`”, “`miter`”]
5153 o stroke-miterlimit (number)
5154 o stroke-opacity (number)
5155 o stroke-width (number) stroke width in pixels, default is '1'
5156 o target (string) used with href
5157 o text (string) contents of the text element. Use `\n` for multiline text
5158 o text-anchor (string) [“`start`”, “`middle`”, “`end`”], default is “`middle`”
5159 o title (string) will create tooltip with a given text
5160 o transform (string) see @Element.transform
5165 * Linear gradient format: “`‹angle›-‹colour›[-‹colour›[:‹offset›]]*-‹colour›`”, example: “`90-#fff-#000`” – 90°
5166 * gradient from white to black or “`0-#fff-#f00:20-#000`” – 0° gradient from white via red (at 20%) to black.
5168 * radial gradient: “`r[(‹fx›, ‹fy›)]‹colour›[-‹colour›[:‹offset›]]*-‹colour›`”, example: “`r#fff-#000`” –
5169 * gradient from white to black or “`r(0.25, 0.75)#fff-#000`” – gradient from white to black with focus point
5170 * at 0.25, 0.75. Focus point coordinates are in 0..1 range. Radial gradients can only be applied to circles and ellipses.
5172 # <p>Please refer to <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 documentation regarding path string</a>. Raphaël fully supports it.</p>
5175 # <li>Colour name (“<code>red</code>”, “<code>green</code>”, “<code>cornflowerblue</code>”, etc)</li>
5176 # <li>#••• — shortened HTML colour: (“<code>#000</code>”, “<code>#fc0</code>”, etc)</li>
5177 # <li>#•••••• — full length HTML colour: (“<code>#000000</code>”, “<code>#bd2300</code>”)</li>
5178 # <li>rgb(•••, •••, •••) — red, green and blue channels’ values: (“<code>rgb(200, 100, 0)</code>”)</li>
5179 # <li>rgb(•••%, •••%, •••%) — same as above, but in %: (“<code>rgb(100%, 175%, 0%)</code>”)</li>
5180 # <li>rgba(•••, •••, •••, •••) — red, green and blue channels’ values: (“<code>rgba(200, 100, 0, .5)</code>”)</li>
5181 # <li>rgba(•••%, •••%, •••%, •••%) — same as above, but in %: (“<code>rgba(100%, 175%, 0%, 50%)</code>”)</li>
5182 # <li>hsb(•••, •••, •••) — hue, saturation and brightness values: (“<code>hsb(0.5, 0.25, 1)</code>”)</li>
5183 # <li>hsb(•••%, •••%, •••%) — same as above, but in %</li>
5184 # <li>hsba(•••, •••, •••, •••) — same as above, but with opacity</li>
5185 # <li>hsl(•••, •••, •••) — almost the same as hsb, see <a href="http://en.wikipedia.org/wiki/HSL_and_HSV" title="HSL and HSV - Wikipedia, the free encyclopedia">Wikipedia page</a></li>
5186 # <li>hsl(•••%, •••%, •••%) — same as above, but in %</li>
5187 # <li>hsla(•••, •••, •••) — same as above, but with opacity</li>
5188 # <li>Optionally for hsb and hsl you could specify hue as a degree: “<code>hsl(240deg, 1, .5)</code>” or, if you want to go fancy, “<code>hsl(240°, 1, .5)</code>”</li>
5191 elproto.attr = function (name, value) {
5197 for (var a in this.attrs) if (this.attrs[has](a)) {
5198 res[a] = this.attrs[a];
5200 res.gradient && res.fill == "none" && (res.fill = res.gradient) && delete res.gradient;
5201 res.transform = this._.transform;
5204 if (value == null && R.is(name, "string")) {
5205 if (name == "fill" && this.attrs.fill == "none" && this.attrs.gradient) {
5206 return this.attrs.gradient;
5208 if (name == "transform") {
5209 return this._.transform;
5211 var names = name.split(separator),
5213 for (var i = 0, ii = names.length; i < ii; i++) {
5215 if (name in this.attrs) {
5216 out[name] = this.attrs[name];
5217 } else if (R.is(this.paper.customAttributes[name], "function")) {
5218 out[name] = this.paper.customAttributes[name].def;
5220 out[name] = R._availableAttrs[name];
5223 return ii - 1 ? out : out[names[0]];
5225 if (value == null && R.is(name, "array")) {
5227 for (i = 0, ii = name.length; i < ii; i++) {
5228 out[name[i]] = this.attr(name[i]);
5232 if (value != null) {
5234 params[name] = value;
5235 } else if (name != null && R.is(name, "object")) {
5238 for (var key in this.paper.customAttributes) if (this.paper.customAttributes[has](key) && params[has](key) && R.is(this.paper.customAttributes[key], "function")) {
5239 var par = this.paper.customAttributes[key].apply(this, [].concat(params[key]));
5240 this.attrs[key] = params[key];
5241 for (var subkey in par) if (par[has](subkey)) {
5242 params[subkey] = par[subkey];
5245 setFillAndStroke(this, params);
5252 * Moves the element so it is the closest to the viewer’s eyes, on top of other elements.
5255 elproto.toFront = function () {
5259 this.node.parentNode.appendChild(this.node);
5260 var svg = this.paper;
5261 svg.top != this && R._tofront(this, svg);
5268 * Moves the element so it is the furthest from the viewer’s eyes, behind other elements.
5271 elproto.toBack = function () {
5275 if (this.node.parentNode.firstChild != this.node) {
5276 this.node.parentNode.insertBefore(this.node, this.node.parentNode.firstChild);
5277 R._toback(this, this.paper);
5278 var svg = this.paper;
5283 * Element.insertAfter
5286 * Inserts current object after the given one.
5289 elproto.insertAfter = function (element) {
5293 var node = element.node || element[element.length - 1].node;
5294 if (node.nextSibling) {
5295 node.parentNode.insertBefore(this.node, node.nextSibling);
5297 node.parentNode.appendChild(this.node);
5299 R._insertafter(this, element, this.paper);
5303 * Element.insertBefore
5306 * Inserts current object before the given one.
5309 elproto.insertBefore = function (element) {
5313 var node = element.node || element[0].node;
5314 node.parentNode.insertBefore(this.node, node);
5315 R._insertbefore(this, element, this.paper);
5318 elproto.blur = function (size) {
5319 // Experimental. No Safari support. Use it on your own risk.
5322 var fltr = $("filter"),
5323 blur = $("feGaussianBlur");
5324 t.attrs.blur = size;
5325 fltr.id = R._createUUID();
5326 $(blur, {stdDeviation: +size || 1.5});
5327 fltr.appendChild(blur);
5328 t.paper.defs.appendChild(fltr);
5330 $(t.node, {filter: "url(#" + fltr.id + ")"});
5333 t._blur.parentNode.removeChild(t._blur);
5335 delete t.attrs.blur;
5337 t.node.removeAttribute("filter");
5340 R._engine.circle = function (svg, x, y, r) {
5341 var el = $("circle");
5342 svg.canvas && svg.canvas.appendChild(el);
5343 var res = new Element(el, svg);
5344 res.attrs = {cx: x, cy: y, r: r, fill: "none", stroke: "#000"};
5345 res.type = "circle";
5349 R._engine.rect = function (svg, x, y, w, h, r) {
5351 svg.canvas && svg.canvas.appendChild(el);
5352 var res = new Element(el, svg);
5353 res.attrs = {x: x, y: y, width: w, height: h, r: r || 0, rx: r || 0, ry: r || 0, fill: "none", stroke: "#000"};
5358 R._engine.ellipse = function (svg, x, y, rx, ry) {
5359 var el = $("ellipse");
5360 svg.canvas && svg.canvas.appendChild(el);
5361 var res = new Element(el, svg);
5362 res.attrs = {cx: x, cy: y, rx: rx, ry: ry, fill: "none", stroke: "#000"};
5363 res.type = "ellipse";
5367 R._engine.image = function (svg, src, x, y, w, h) {
5368 var el = $("image");
5369 $(el, {x: x, y: y, width: w, height: h, preserveAspectRatio: "none"});
5370 el.setAttributeNS(xlink, "href", src);
5371 svg.canvas && svg.canvas.appendChild(el);
5372 var res = new Element(el, svg);
5373 res.attrs = {x: x, y: y, width: w, height: h, src: src};
5377 R._engine.text = function (svg, x, y, text) {
5379 // $(el, {x: x, y: y, "text-anchor": "middle"});
5380 svg.canvas && svg.canvas.appendChild(el);
5381 var res = new Element(el, svg);
5385 "text-anchor": "middle",
5387 font: R._availableAttrs.font,
5392 setFillAndStroke(res, res.attrs);
5395 R._engine.setSize = function (width, height) {
5396 this.width = width || this.width;
5397 this.height = height || this.height;
5398 this.canvas.setAttribute("width", this.width);
5399 this.canvas.setAttribute("height", this.height);
5400 if (this._viewBox) {
5401 this.setViewBox.apply(this, this._viewBox);
5405 R._engine.create = function () {
5406 var con = R._getContainer.apply(0, arguments),
5407 container = con && con.container,
5411 height = con.height;
5413 throw new Error("SVG container not found.");
5415 var cnvs = $("svg"),
5416 css = "overflow:hidden;",
5420 width = width || 512;
5421 height = height || 342;
5426 xmlns: "http://www.w3.org/2000/svg"
5428 if (container == 1) {
5429 cnvs.style.cssText = css + "position:absolute;left:" + x + "px;top:" + y + "px";
5430 R._g.doc.body.appendChild(cnvs);
5433 cnvs.style.cssText = css + "position:relative";
5434 if (container.firstChild) {
5435 container.insertBefore(cnvs, container.firstChild);
5437 container.appendChild(cnvs);
5440 container = new R._Paper;
5441 container.width = width;
5442 container.height = height;
5443 container.canvas = cnvs;
5444 // plugins.call(container, container, R.fn);
5446 container._left = container._top = 0;
5447 isFloating && (container.renderfix = function () {});
5448 container.renderfix();
5451 R._engine.setViewBox = function (x, y, w, h, fit) {
5452 eve("setViewBox", this, this._viewBox, [x, y, w, h, fit]);
5453 var size = mmax(w / this.width, h / this.height),
5455 aspectRatio = fit ? "meet" : "xMinYMin",
5462 delete this._vbSize;
5463 vb = "0 0 " + this.width + S + this.height;
5465 this._vbSize = size;
5466 vb = x + S + y + S + w + S + h;
5470 preserveAspectRatio: aspectRatio
5472 while (size && top) {
5473 sw = "stroke-width" in top.attrs ? top.attrs["stroke-width"] : 1;
5474 top.attr({"stroke-width": sw});
5479 this._viewBox = [x, y, w, h, !!fit];
5486 * Fixes the issue of Firefox and IE9 regarding subpixel rendering. If paper is dependant
5487 * on other elements after reflow it could shift half pixel which cause for lines to lost their crispness.
5488 * This method fixes the issue.
5490 Special thanks to Mariusz Nowak (http://www.medikoo.com/) for this method.
5492 R.prototype.renderfix = function () {
5493 var cnvs = this.canvas,
5495 pos = cnvs.getScreenCTM(),
5500 this._left = (this._left + left) % 1;
5501 s.left = this._left + "px";
5504 this._top = (this._top + top) % 1;
5505 s.top = this._top + "px";
5513 * Clears the paper, i.e. removes all the elements.
5515 R.prototype.clear = function () {
5516 R.eve("clear", this);
5517 var c = this.canvas;
5518 while (c.firstChild) {
5519 c.removeChild(c.firstChild);
5521 this.bottom = this.top = null;
5522 (this.desc = $("desc")).appendChild(R._g.doc.createTextNode("Created with Rapha\xebl " + R.version));
5523 c.appendChild(this.desc);
5524 c.appendChild(this.defs = $("defs"));
5530 * Removes the paper from the DOM.
5532 R.prototype.remove = function () {
5533 eve("remove", this);
5534 this.canvas.parentNode && this.canvas.parentNode.removeChild(this.canvas);
5535 for (var i in this) {
5536 this[i] = removed(i);
5539 var setproto = R.st;
5540 for (var method in elproto) if (elproto[has](method) && !setproto[has](method)) {
5541 setproto[method] = (function (methodname) {
5542 return function () {
5543 var arg = arguments;
5544 return this.forEach(function (el) {
5545 el[methodname].apply(el, arg);
5552 // ┌─────────────────────────────────────────────────────────────────────┐ \\
5553 // │ Raphaël 2 - JavaScript Vector Library │ \\
5554 // ├─────────────────────────────────────────────────────────────────────┤ \\
5555 // │ VML Module │ \\
5556 // ├─────────────────────────────────────────────────────────────────────┤ \\
5557 // │ Copyright (c) 2008-2011 Dmitry Baranovskiy (http://raphaeljs.com) │ \\
5558 // │ Copyright (c) 2008-2011 Sencha Labs (http://sencha.com) │ \\
5559 // │ Licensed under the MIT (http://raphaeljs.com/license.html) license. │ \\
5560 // └─────────────────────────────────────────────────────────────────────┘ \\
5561 window.Raphael.vml && function (R) {
5562 var has = "hasOwnProperty",
5564 toFloat = parseFloat,
5570 fillString = "fill",
5571 separator = /[, ]+/,
5576 var map = {M: "m", L: "l", C: "c", Z: "x", m: "t", l: "r", c: "v", z: "x"},
5577 bites = /([clmz]),?([^clmz]*)/gi,
5578 blurregexp = / progid:\S+Blur\([^\)]+\)/g,
5579 val = /-?[^,\s-]+/g,
5580 cssDot = "position:absolute;left:0;top:0;width:1px;height:1px",
5582 pathTypes = {path: 1, rect: 1},
5583 ovalTypes = {circle: 1, ellipse: 1},
5584 path2vml = function (path) {
5585 var total = /[ahqstv]/ig,
5586 command = R._pathToAbsolute;
5587 Str(path).match(total) && (command = path2curve);
5589 if (command == R._pathToAbsolute && !Str(path).match(total)) {
5590 var res = Str(path).replace(bites, function (all, command, args) {
5592 isMove = command.toLowerCase() == "m",
5594 args.replace(val, function (value) {
5595 if (isMove && vals.length == 2) {
5596 res += vals + map[command == "m" ? "l" : "L"];
5599 vals.push(round(value * zoom));
5605 var pa = command(path), p, r;
5607 for (var i = 0, ii = pa.length; i < ii; i++) {
5609 r = pa[i][0].toLowerCase();
5610 r == "z" && (r = "x");
5611 for (var j = 1, jj = p.length; j < jj; j++) {
5612 r += round(p[j] * zoom) + (j != jj - 1 ? "," : E);
5618 compensation = function (deg, dx, dy) {
5620 m.rotate(-deg, .5, .5);
5626 setCoords = function (p, sx, sy, dx, dy, deg) {
5629 fillpos = _.fillpos,
5637 s.visibility = "hidden";
5641 o.coordsize = abs(kx) + S + abs(ky);
5642 s.rotation = deg * (sx * sy < 0 ? -1 : 1);
5644 var c = compensation(deg, dx, dy);
5648 sx < 0 && (flip += "x");
5649 sy < 0 && (flip += " y") && (y = -1);
5651 o.coordorigin = (dx * -kx) + S + (dy * -ky);
5652 if (fillpos || _.fillsize) {
5653 var fill = o.getElementsByTagName(fillString);
5654 fill = fill && fill[0];
5655 o.removeChild(fill);
5657 c = compensation(deg, m.x(fillpos[0], fillpos[1]), m.y(fillpos[0], fillpos[1]));
5658 fill.position = c.dx * y + S + c.dy * y;
5661 fill.size = _.fillsize[0] * abs(sx) + S + _.fillsize[1] * abs(sy);
5663 o.appendChild(fill);
5665 s.visibility = "visible";
5667 R.toString = function () {
5668 return "Your browser doesn\u2019t support SVG. Falling down to VML.\nYou are running Rapha\xebl " + this.version;
5670 addArrow = function (o, value, isEnd) {
5671 var values = Str(value).toLowerCase().split("-"),
5672 se = isEnd ? "end" : "start",
5678 switch (values[i]) {
5688 case "narrow": h = values[i]; break;
5690 case "short": w = values[i]; break;
5693 var stroke = o.node.getElementsByTagName("stroke")[0];
5694 stroke[se + "arrow"] = type;
5695 stroke[se + "arrowlength"] = w;
5696 stroke[se + "arrowwidth"] = h;
5698 setFillAndStroke = function (o, params) {
5699 // o.paper.canvas.style.display = "none";
5700 o.attrs = o.attrs || {};
5705 newpath = pathTypes[o.type] && (params.x != a.x || params.y != a.y || params.width != a.width || params.height != a.height || params.cx != a.cx || params.cy != a.cy || params.rx != a.rx || params.ry != a.ry || params.r != a.r),
5706 isOval = ovalTypes[o.type] && (a.cx != params.cx || a.cy != params.cy || a.r != params.r || a.rx != params.rx || a.ry != params.ry),
5710 for (var par in params) if (params[has](par)) {
5711 a[par] = params[par];
5714 a.path = R._getPath[o.type](o);
5717 params.href && (node.href = params.href);
5718 params.title && (node.title = params.title);
5719 params.target && (node.target = params.target);
5720 params.cursor && (s.cursor = params.cursor);
5721 "blur" in params && o.blur(params.blur);
5722 "transform" in params && o.transform(params.transform);
5723 if (params.path && o.type == "path" || newpath) {
5724 node.path = path2vml(a.path);
5729 rx = a.rx || a.r || 0,
5730 ry = a.ry || a.r || 0;
5731 node.path = R.format("ar{0},{1},{2},{3},{4},{1},{4},{1}x", round((cx - rx) * zoom), round((cy - ry) * zoom), round((cx + rx) * zoom), round((cy + ry) * zoom), round(cx * zoom));
5733 if ("clip-rect" in params) {
5734 var rect = Str(params["clip-rect"]).split(separator);
5735 if (rect.length == 4) {
5736 rect[2] = +rect[2] + (+rect[0]);
5737 rect[3] = +rect[3] + (+rect[1]);
5738 var div = node.clipRect || R._g.doc.createElement("div"),
5740 group = node.parentNode;
5741 dstyle.clip = R.format("rect({1}px {2}px {3}px {0}px)", rect);
5742 if (!node.clipRect) {
5743 dstyle.position = "absolute";
5746 dstyle.width = o.paper.width + "px";
5747 dstyle.height = o.paper.height + "px";
5748 group.parentNode.insertBefore(div, group);
5749 div.appendChild(group);
5750 node.clipRect = div;
5753 if (!params["clip-rect"]) {
5754 node.clipRect && (node.clipRect.style.clip = E);
5758 var textpathStyle = o.textpath.style;
5759 params.font && (textpathStyle.font = params.font);
5760 params["font-family"] && (textpathStyle.fontFamily = '"' + params["font-family"].split(",")[0].replace(/^['"]+|['"]+$/g, E) + '"');
5761 params["font-size"] && (textpathStyle.fontSize = params["font-size"]);
5762 params["font-weight"] && (textpathStyle.fontWeight = params["font-weight"]);
5763 params["font-style"] && (textpathStyle.fontStyle = params["font-style"]);
5765 if ("arrow-start" in params) {
5766 addArrow(res, params["arrow-start"]);
5768 if ("arrow-end" in params) {
5769 addArrow(res, params["arrow-end"], 1);
5771 if (params.opacity != null ||
5772 params["stroke-width"] != null ||
5773 params.fill != null ||
5774 params.src != null ||
5775 params.stroke != null ||
5776 params["stroke-width"] != null ||
5777 params["stroke-opacity"] != null ||
5778 params["fill-opacity"] != null ||
5779 params["stroke-dasharray"] != null ||
5780 params["stroke-miterlimit"] != null ||
5781 params["stroke-linejoin"] != null ||
5782 params["stroke-linecap"] != null) {
5783 var fill = node.getElementsByTagName(fillString),
5785 fill = fill && fill[0];
5786 !fill && (newfill = fill = createNode(fillString));
5787 if (o.type == "image" && params.src) {
5788 fill.src = params.src;
5790 params.fill && (fill.on = true);
5791 if (fill.on == null || params.fill == "none" || params.fill === null) {
5794 if (fill.on && params.fill) {
5795 var isURL = Str(params.fill).match(R._ISURL);
5797 fill.parentNode == node && node.removeChild(fill);
5799 fill.src = isURL[1];
5801 var bbox = o.getBBox(1);
5802 fill.position = bbox.x + S + bbox.y;
5803 o._.fillpos = [bbox.x, bbox.y];
5805 R._preload(isURL[1], function () {
5806 o._.fillsize = [this.offsetWidth, this.offsetHeight];
5809 fill.color = R.getRGB(params.fill).hex;
5811 fill.type = "solid";
5812 if (R.getRGB(params.fill).error && (res.type in {circle: 1, ellipse: 1} || Str(params.fill).charAt() != "r") && addGradientFill(res, params.fill, fill)) {
5814 a.gradient = params.fill;
5815 fill.rotate = false;
5819 if ("fill-opacity" in params || "opacity" in params) {
5820 var opacity = ((+a["fill-opacity"] + 1 || 2) - 1) * ((+a.opacity + 1 || 2) - 1) * ((+R.getRGB(params.fill).o + 1 || 2) - 1);
5821 opacity = mmin(mmax(opacity, 0), 1);
5822 fill.opacity = opacity;
5824 fill.color = "none";
5827 node.appendChild(fill);
5828 var stroke = (node.getElementsByTagName("stroke") && node.getElementsByTagName("stroke")[0]),
5830 !stroke && (newstroke = stroke = createNode("stroke"));
5831 if ((params.stroke && params.stroke != "none") ||
5832 params["stroke-width"] ||
5833 params["stroke-opacity"] != null ||
5834 params["stroke-dasharray"] ||
5835 params["stroke-miterlimit"] ||
5836 params["stroke-linejoin"] ||
5837 params["stroke-linecap"]) {
5840 (params.stroke == "none" || params.stroke === null || stroke.on == null || params.stroke == 0 || params["stroke-width"] == 0) && (stroke.on = false);
5841 var strokeColor = R.getRGB(params.stroke);
5842 stroke.on && params.stroke && (stroke.color = strokeColor.hex);
5843 opacity = ((+a["stroke-opacity"] + 1 || 2) - 1) * ((+a.opacity + 1 || 2) - 1) * ((+strokeColor.o + 1 || 2) - 1);
5844 var width = (toFloat(params["stroke-width"]) || 1) * .75;
5845 opacity = mmin(mmax(opacity, 0), 1);
5846 params["stroke-width"] == null && (width = a["stroke-width"]);
5847 params["stroke-width"] && (stroke.weight = width);
5848 width && width < 1 && (opacity *= width) && (stroke.weight = 1);
5849 stroke.opacity = opacity;
5851 params["stroke-linejoin"] && (stroke.joinstyle = params["stroke-linejoin"] || "miter");
5852 stroke.miterlimit = params["stroke-miterlimit"] || 8;
5853 params["stroke-linecap"] && (stroke.endcap = params["stroke-linecap"] == "butt" ? "flat" : params["stroke-linecap"] == "square" ? "square" : "round");
5854 if (params["stroke-dasharray"]) {
5858 "-.": "shortdashdot",
5859 "-..": "shortdashdotdot",
5864 "--.": "longdashdot",
5865 "--..": "longdashdotdot"
5867 stroke.dashstyle = dasharray[has](params["stroke-dasharray"]) ? dasharray[params["stroke-dasharray"]] : E;
5869 newstroke && node.appendChild(stroke);
5871 if (res.type == "text") {
5872 res.paper.canvas.style.display = E;
5873 var span = res.paper.span,
5875 fontSize = a.font && a.font.match(/\d+(?:\.\d*)?(?=px)/);
5877 a.font && (s.font = a.font);
5878 a["font-family"] && (s.fontFamily = a["font-family"]);
5879 a["font-weight"] && (s.fontWeight = a["font-weight"]);
5880 a["font-style"] && (s.fontStyle = a["font-style"]);
5881 fontSize = toFloat(fontSize ? fontSize[0] : a["font-size"]);
5882 s.fontSize = fontSize * m + "px";
5883 res.textpath.string && (span.innerHTML = Str(res.textpath.string).replace(/</g, "<").replace(/&/g, "&").replace(/\n/g, "<br>"));
5884 var brect = span.getBoundingClientRect();
5885 res.W = a.w = (brect.right - brect.left) / m;
5886 res.H = a.h = (brect.bottom - brect.top) / m;
5887 res.paper.canvas.style.display = "none";
5889 res.Y = a.y + res.H / 2;
5891 ("x" in params || "y" in params) && (res.path.v = R.format("m{0},{1}l{2},{1}", round(a.x * zoom), round(a.y * zoom), round(a.x * zoom) + 1));
5892 var dirtyattrs = ["x", "y", "text", "font", "font-family", "font-weight", "font-style", "font-size"];
5893 for (var d = 0, dd = dirtyattrs.length; d < dd; d++) if (dirtyattrs[d] in params) {
5898 // text-anchor emulation
5899 switch (a["text-anchor"]) {
5901 res.textpath.style["v-text-align"] = "left";
5902 res.bbx = res.W / 2;
5905 res.textpath.style["v-text-align"] = "right";
5906 res.bbx = -res.W / 2;
5909 res.textpath.style["v-text-align"] = "center";
5913 res.textpath.style["v-text-kern"] = true;
5915 // res.paper.canvas.style.display = E;
5917 addGradientFill = function (o, gradient, fill) {
5918 o.attrs = o.attrs || {};
5919 var attrs = o.attrs,
5924 o.attrs.gradient = gradient;
5925 gradient = Str(gradient).replace(R._radial_gradient, function (all, fx, fy) {
5930 pow(fx - .5, 2) + pow(fy - .5, 2) > .25 && (fy = math.sqrt(.25 - pow(fx - .5, 2)) * ((fy > .5) * 2 - 1) + .5);
5935 gradient = gradient.split(/\s*\-\s*/);
5936 if (type == "linear") {
5937 var angle = gradient.shift();
5938 angle = -toFloat(angle);
5943 var dots = R._parseDots(gradient);
5947 o = o.shape || o.node;
5949 o.removeChild(fill);
5951 fill.method = "none";
5952 fill.color = dots[0].color;
5953 fill.color2 = dots[dots.length - 1].color;
5955 for (var i = 0, ii = dots.length; i < ii; i++) {
5956 dots[i].offset && clrs.push(dots[i].offset + S + dots[i].color);
5958 fill.colors = clrs.length ? clrs.join() : "0% " + fill.color;
5959 if (type == "radial") {
5960 fill.type = "gradientTitle";
5961 fill.focus = "100%";
5962 fill.focussize = "0 0";
5963 fill.focusposition = fxfy;
5966 // fill.rotate= true;
5967 fill.type = "gradient";
5968 fill.angle = (270 - angle) % 360;
5970 o.appendChild(fill);
5974 Element = function (node, vml) {
5975 this[0] = this.node = node;
5976 node.raphael = true;
5978 node.raphaelid = this.id;
5983 this.matrix = R.matrix();
5994 !vml.bottom && (vml.bottom = this);
5995 this.prev = vml.top;
5996 vml.top && (vml.top.next = this);
6002 Element.prototype = elproto;
6003 elproto.constructor = Element;
6004 elproto.transform = function (tstr) {
6006 return this._.transform;
6008 R._extractTransform(this, tstr);
6009 var matrix = this.matrix.clone(),
6010 vbs = this.paper._viewBoxShift,
6014 isGrad = Str(this.attrs.fill).indexOf("-") + 1;
6015 matrix.translate(-.5, -.5);
6017 matrix.scale(vbs.scale, vbs.scale, -1, -1);
6018 matrix.translate(vbs.dx, vbs.dy);
6020 if (isGrad || this.type == "image") {
6021 skew.matrix = "1 0 0 1";
6022 skew.offset = "0 0";
6023 split = matrix.split();
6024 if ((isGrad && split.noRotation) || !split.isSimple) {
6025 o.style.filter = matrix.toFilter();
6026 var bb = this.getBBox(),
6027 bbt = this.getBBox(1),
6030 o.coordorigin = (dx * -zoom) + S + (dy * -zoom);
6031 setCoords(this, 1, 1, dx, dy, 0);
6034 setCoords(this, split.scalex, split.scaley, split.dx, split.dy, split.rotate);
6038 skew.matrix = Str(matrix);
6039 skew.offset = matrix.offset();
6043 elproto.rotate = function (deg, cx, cy) {
6050 deg = Str(deg).split(separator);
6051 if (deg.length - 1) {
6052 cx = toFloat(deg[1]);
6053 cy = toFloat(deg[2]);
6055 deg = toFloat(deg[0]);
6056 (cy == null) && (cx = cy);
6057 if (cx == null || cy == null) {
6058 var bbox = this.getBBox(1);
6059 cx = bbox.x + bbox.width / 2;
6060 cy = bbox.y + bbox.height / 2;
6063 this.transform(this._.transform.concat([["r", deg, cx, cy]]));
6066 elproto.translate = function (dx, dy) {
6070 dx = Str(dx).split(separator);
6071 if (dx.length - 1) {
6072 dy = toFloat(dx[1]);
6074 dx = toFloat(dx[0]) || 0;
6077 this._.bbox.x += dx;
6078 this._.bbox.y += dy;
6080 this.transform(this._.transform.concat([["t", dx, dy]]));
6083 elproto.scale = function (sx, sy, cx, cy) {
6087 sx = Str(sx).split(separator);
6088 if (sx.length - 1) {
6089 sy = toFloat(sx[1]);
6090 cx = toFloat(sx[2]);
6091 cy = toFloat(sx[3]);
6092 isNaN(cx) && (cx = null);
6093 isNaN(cy) && (cy = null);
6095 sx = toFloat(sx[0]);
6096 (sy == null) && (sy = sx);
6097 (cy == null) && (cx = cy);
6098 if (cx == null || cy == null) {
6099 var bbox = this.getBBox(1);
6101 cx = cx == null ? bbox.x + bbox.width / 2 : cx;
6102 cy = cy == null ? bbox.y + bbox.height / 2 : cy;
6104 this.transform(this._.transform.concat([["s", sx, sy, cx, cy]]));
6108 elproto.hide = function () {
6109 !this.removed && (this.node.style.display = "none");
6112 elproto.show = function () {
6113 !this.removed && (this.node.style.display = E);
6116 elproto._getBBox = function () {
6120 if (this.type == "text") {
6122 x: this.X + (this.bbx || 0) - this.W / 2,
6128 return pathDimensions(this.attrs.path);
6131 elproto.remove = function () {
6135 R.eve.unbind("*.*." + this.id);
6136 R._tear(this, this.paper);
6137 this.node.parentNode.removeChild(this.node);
6138 this.shape && this.shape.parentNode.removeChild(this.shape);
6139 for (var i in this) {
6142 this.removed = true;
6144 elproto.attr = function (name, value) {
6150 for (var a in this.attrs) if (this.attrs[has](a)) {
6151 res[a] = this.attrs[a];
6153 res.gradient && res.fill == "none" && (res.fill = res.gradient) && delete res.gradient;
6154 res.transform = this._.transform;
6157 if (value == null && R.is(name, "string")) {
6158 if (name == fillString && this.attrs.fill == "none" && this.attrs.gradient) {
6159 return this.attrs.gradient;
6161 var names = name.split(separator),
6163 for (var i = 0, ii = names.length; i < ii; i++) {
6165 if (name in this.attrs) {
6166 out[name] = this.attrs[name];
6167 } else if (R.is(this.paper.customAttributes[name], "function")) {
6168 out[name] = this.paper.customAttributes[name].def;
6170 out[name] = R._availableAttrs[name];
6173 return ii - 1 ? out : out[names[0]];
6175 if (this.attrs && value == null && R.is(name, "array")) {
6177 for (i = 0, ii = name.length; i < ii; i++) {
6178 out[name[i]] = this.attr(name[i]);
6183 if (value != null) {
6185 params[name] = value;
6187 value == null && R.is(name, "object") && (params = name);
6188 for (var key in params) {
6189 R.eve("attr." + key + "." + this.id, this, params[key]);
6192 for (key in this.paper.customAttributes) if (this.paper.customAttributes[has](key) && params[has](key) && R.is(this.paper.customAttributes[key], "function")) {
6193 var par = this.paper.customAttributes[key].apply(this, [][concat](params[key]));
6194 this.attrs[key] = params[key];
6195 for (var subkey in par) if (par[has](subkey)) {
6196 params[subkey] = par[subkey];
6199 // this.paper.canvas.style.display = "none";
6200 if (params.text && this.type == "text") {
6201 this.textpath.string = params.text;
6203 setFillAndStroke(this, params);
6204 // this.paper.canvas.style.display = E;
6208 elproto.toFront = function () {
6209 !this.removed && this.node.parentNode.appendChild(this.node);
6210 this.paper && this.paper.top != this && tofront(this, this.paper);
6213 elproto.toBack = function () {
6217 if (this.node.parentNode.firstChild != this.node) {
6218 this.node.parentNode.insertBefore(this.node, this.node.parentNode.firstChild);
6219 toback(this, this.paper);
6223 elproto.insertAfter = function (element) {
6227 if (element.constructor == Set) {
6228 element = element[element.length - 1];
6230 if (element.node.nextSibling) {
6231 element.node.parentNode.insertBefore(this.node, element.node.nextSibling);
6233 element.node.parentNode.appendChild(this.node);
6235 R._insertafter(this, element, this.paper);
6238 elproto.insertBefore = function (element) {
6242 if (element.constructor == Set) {
6243 element = element[0];
6245 element.node.parentNode.insertBefore(this.node, element.node);
6246 R._insertbefore(this, element, this.paper);
6249 elproto.blur = function (size) {
6250 var s = this.node.runtimeStyle,
6252 f = f.replace(blurregexp, E);
6254 this.attrs.blur = size;
6255 s.filter = f + S + ms + ".Blur(pixelradius=" + (+size || 1.5) + ")";
6256 s.margin = R.format("-{0}px 0 0 -{0}px", round(+size || 1.5));
6260 delete this.attrs.blur;
6264 R._engine.path = function (pathString, vml) {
6265 var el = createNode("shape");
6266 el.style.cssText = cssDot;
6267 el.coordsize = zoom + S + zoom;
6268 el.coordorigin = vml.coordorigin;
6269 var p = new Element(el, vml),
6270 attr = {fill: "none", stroke: "#000"};
6271 pathString && (attr.path = pathString);
6275 setFillAndStroke(p, attr);
6276 vml.canvas.appendChild(el);
6277 var skew = createNode("skew");
6279 el.appendChild(skew);
6284 R._engine.rect = function (vml, x, y, w, h, r) {
6285 var path = R._rectPath(x, y, w, h, r),
6286 res = vml.path(path),
6290 res.W = a.width = w;
6291 res.H = a.height = h;
6297 R._engine.ellipse = function (vml, x, y, rx, ry) {
6298 var res = vml.path(),
6304 res.type = "ellipse";
6305 setFillAndStroke(res, {
6313 R._engine.circle = function (vml, x, y, r) {
6314 var res = vml.path(),
6318 res.W = res.H = r * 2;
6319 res.type = "circle";
6320 setFillAndStroke(res, {
6327 R._engine.image = function (vml, src, x, y, w, h) {
6328 var path = R._rectPath(x, y, w, h),
6329 res = vml.path(path).attr({stroke: "none"}),
6332 fill = node.getElementsByTagName(fillString)[0];
6336 res.W = a.width = w;
6337 res.H = a.height = h;
6340 fill.parentNode == node && node.removeChild(fill);
6344 res._.fillpos = [x, y];
6345 res._.fillsize = [w, h];
6346 node.appendChild(fill);
6347 setCoords(res, 1, 1, 0, 0, 0);
6350 R._engine.text = function (vml, x, y, text) {
6351 var el = createNode("shape"),
6352 path = createNode("path"),
6353 o = createNode("textpath");
6357 path.v = R.format("m{0},{1}l{2},{1}", round(x * zoom), round(y * zoom), round(x * zoom) + 1);
6358 path.textpathok = true;
6359 o.string = Str(text);
6361 el.style.cssText = "position:absolute;left:0;top:0;width:1px;height:1px";
6362 el.coordsize = zoom + S + zoom;
6363 el.coordorigin = "0 0";
6364 var p = new Element(el, vml),
6365 attr = {fill: "#000", stroke: "none", font: availableAttrs.font, text: text};
6370 p.attrs.text = Str(text);
6375 setFillAndStroke(p, attr);
6377 el.appendChild(path);
6378 vml.canvas.appendChild(el);
6379 var skew = createNode("skew");
6381 el.appendChild(skew);
6386 R._engine.setSize = function (width, height) {
6387 var cs = this.canvas.style;
6389 this.height = height;
6390 width == +width && (width += "px");
6391 height == +height && (height += "px");
6394 cs.clip = "rect(0 " + width + " " + height + " 0)";
6395 if (this._viewBox) {
6396 setViewBox.apply(this, this._viewBox);
6400 R._engine.setViewBox = function (x, y, w, h, fit) {
6401 R.eve("setViewBox", this, this._viewBox, [x, y, w, h, fit]);
6402 var width = this.width,
6403 height = this.height,
6404 size = 1 / mmax(w / width, h / height),
6409 if (w * H < width) {
6410 x -= (width - w * H) / 2 / H;
6412 if (h * W < height) {
6413 y -= (height - h * W) / 2 / W;
6416 this._viewBox = [x, y, w, h, !!fit];
6417 this._viewBoxShift = {
6422 this.forEach(function (el) {
6423 el.transform("...");
6428 initWin = function (win) {
6429 var doc = win.document;
6430 doc.createStyleSheet().addRule(".rvml", "behavior:url(#default#VML)");
6432 !doc.namespaces.rvml && doc.namespaces.add("rvml", "urn:schemas-microsoft-com:vml");
6433 createNode = function (tagName) {
6434 return doc.createElement('<rvml:' + tagName + ' class="rvml">');
6437 createNode = function (tagName) {
6438 return doc.createElement('<' + tagName + ' xmlns="urn:schemas-microsoft.com:vml" class="rvml">');
6443 R._engine.create = function () {
6444 var con = R._getContainer.apply(0, arguments),
6445 container = con.container,
6446 height = con.height,
6452 throw new Error("VML container not found.");
6454 var res = new R._Paper,
6455 c = res.canvas = R._g.doc.createElement("div"),
6459 width = width || 512;
6460 height = height || 342;
6462 res.height = height;
6463 width == +width && (width += "px");
6464 height == +height && (height += "px");
6465 res.coordsize = zoom * 1e3 + S + zoom * 1e3;
6466 res.coordorigin = "0 0";
6467 res.span = R._g.doc.createElement("span");
6468 res.span.style.cssText = "position:absolute;left:-9999em;top:-9999em;padding:0;margin:0;line-height:1;";
6469 c.appendChild(res.span);
6470 cs.cssText = R.format("top:0;left:0;width:{0};height:{1};display:inline-block;position:relative;clip:rect(0 {0} {1} 0);overflow:hidden", width, height);
6471 if (container == 1) {
6472 R._g.doc.body.appendChild(c);
6475 cs.position = "absolute";
6477 if (container.firstChild) {
6478 container.insertBefore(c, container.firstChild);
6480 container.appendChild(c);
6483 // plugins.call(res, res, R.fn);
6484 res.renderfix = function () {};
6487 R.prototype.clear = function () {
6488 R.eve("clear", this);
6489 this.canvas.innerHTML = E;
6490 this.span = R._g.doc.createElement("span");
6491 this.span.style.cssText = "position:absolute;left:-9999em;top:-9999em;padding:0;margin:0;line-height:1;display:inline;";
6492 this.canvas.appendChild(this.span);
6493 this.bottom = this.top = null;
6495 R.prototype.remove = function () {
6496 R.eve("remove", this);
6497 this.canvas.parentNode.removeChild(this.canvas);
6498 for (var i in this) {
6499 this[i] = removed(i);