jcanvas.js 107 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365
/**
 * @license jCanvas v20.1.3
 * Copyright 2017 Caleb Evans
 * Released under the MIT license
 */
(function (jQuery, global, base_factory) {
	'use strict';

	if (typeof module === 'object' && typeof module.exports === 'object') {
		module.exports = function (jQuery, w) {
			return base_factory(jQuery, w);
		};
	} else {
		base_factory(jQuery, global);
	}

// Pass this if window is not defined yet
}(typeof window !== 'undefined' ? window.jQuery : {}, typeof window !== 'undefined' ? window : this, function ($, window) {
'use strict';

var document = window.document,
	Image = window.Image,
	Array = window.Array,
	getComputedStyle = window.getComputedStyle,
	Math = window.Math,
	Number = window.Number,
	parseFloat = window.parseFloat;

// Define local aliases to frequently used properties
var defaults,
	// Aliases to jQuery methods
	extendObject = $.extend,
	inArray = $.inArray,
	typeOf = function (operand) {
		return Object.prototype.toString.call(operand)
			.slice(8, -1).toLowerCase();
	},
	isFunction = $.isFunction,
	isPlainObject = $.isPlainObject,
	// Math constants and functions
	PI = Math.PI,
	round = Math.round,
	abs = Math.abs,
	sin = Math.sin,
	cos = Math.cos,
	atan2 = Math.atan2,
	// The Array slice() method
	arraySlice = Array.prototype.slice,
	// jQuery's internal event normalization function
	jQueryEventFix = $.event.fix,
	// Object for storing a number of internal property maps
	maps = {},
	// jQuery internal caches
	caches = {
		dataCache: {},
		propCache: {},
		imageCache: {}
	},
	// Base transformations
	baseTransforms = {
		rotate: 0,
		scaleX: 1,
		scaleY: 1,
		translateX: 0,
		translateY: 0,
		// Store all previous masks
		masks: []
	},
	// Object for storing CSS-related properties
	css = {},
	tangibleEvents = [
		'mousedown',
		'mousemove',
		'mouseup',
		'mouseover',
		'mouseout',
		'touchstart',
		'touchmove',
		'touchend'
	];

// Constructor for creating objects that inherit from jCanvas preferences and defaults
function jCanvasObject(args) {
	var params = this,
		propName;
	// Copy the given parameters into new object
	for (propName in args) {
		// Do not merge defaults into parameters
		if (Object.prototype.hasOwnProperty.call(args, propName)) {
			params[propName] = args[propName];
		}
	}
	return params;
}

// jCanvas object in which global settings are other data are stored
var jCanvas = {
	// Events object for storing jCanvas event initiation functions
	events: {},
	// Object containing all jCanvas event hooks
	eventHooks: {},
	// Settings for enabling future jCanvas features
	future: {}
};

// jCanvas default property values
function jCanvasDefaults() {
	extendObject(this, jCanvasDefaults.baseDefaults);
}
jCanvasDefaults.baseDefaults = {
	align: 'center',
	arrowAngle: 90,
	arrowRadius: 0,
	autosave: true,
	baseline: 'middle',
	bringToFront: false,
	ccw: false,
	closed: false,
	compositing: 'source-over',
	concavity: 0,
	cornerRadius: 0,
	count: 1,
	cropFromCenter: true,
	crossOrigin: null,
	cursors: null,
	disableEvents: false,
	draggable: false,
	dragGroups: null,
	groups: null,
	data: null,
	dx: null,
	dy: null,
	end: 360,
	eventX: null,
	eventY: null,
	fillStyle: 'transparent',
	fontStyle: 'normal',
	fontSize: '12pt',
	fontFamily: 'sans-serif',
	fromCenter: true,
	height: null,
	imageSmoothing: true,
	inDegrees: true,
	intangible: false,
	index: null,
	letterSpacing: null,
	lineHeight: 1,
	layer: false,
	mask: false,
	maxWidth: null,
	miterLimit: 10,
	name: null,
	opacity: 1,
	r1: null,
	r2: null,
	radius: 0,
	repeat: 'repeat',
	respectAlign: false,
	restrictDragToAxis: null,
	rotate: 0,
	rounded: false,
	scale: 1,
	scaleX: 1,
	scaleY: 1,
	shadowBlur: 0,
	shadowColor: 'transparent',
	shadowStroke: false,
	shadowX: 0,
	shadowY: 0,
	sHeight: null,
	sides: 0,
	source: '',
	spread: 0,
	start: 0,
	strokeCap: 'butt',
	strokeDash: null,
	strokeDashOffset: 0,
	strokeJoin: 'miter',
	strokeStyle: 'transparent',
	strokeWidth: 1,
	sWidth: null,
	sx: null,
	sy: null,
	text: '',
	translate: 0,
	translateX: 0,
	translateY: 0,
	type: null,
	visible: true,
	width: null,
	x: 0,
	y: 0
};
defaults = new jCanvasDefaults();
jCanvasObject.prototype = defaults;

/* Internal helper methods */

// Determines if the given operand is a string
function isString(operand) {
	return (typeOf(operand) === 'string');
}

// Determines if the given operand is numeric
function isNumeric(operand) {
	return !isNaN(Number(operand)) && !isNaN(parseFloat(operand));
}

// Get 2D context for the given canvas
function _getContext(canvas) {
	return (canvas && canvas.getContext ? canvas.getContext('2d') : null);
}

// Coerce designated number properties from strings to numbers
function _coerceNumericProps(props) {
	var propName, propType, propValue;
	// Loop through all properties in given property map
	for (propName in props) {
		if (Object.prototype.hasOwnProperty.call(props, propName)) {
			propValue = props[propName];
			propType = typeOf(propValue);
			// If property is non-empty string and value is numeric
			if (propType === 'string' && isNumeric(propValue) && propName !== 'text') {
				// Convert value to number
				props[propName] = parseFloat(propValue);
			}
		}
	}
	// Ensure value of text property is always a string
	if (props.text !== undefined) {
		props.text = String(props.text);
	}
}

// Clone the given transformations object
function _cloneTransforms(transforms) {
	// Clone the object itself
	transforms = extendObject({}, transforms);
	// Clone the object's masks array
	transforms.masks = transforms.masks.slice(0);
	return transforms;
}

// Save canvas context and update transformation stack
function _saveCanvas(ctx, data) {
	var transforms;
	ctx.save();
	transforms = _cloneTransforms(data.transforms);
	data.savedTransforms.push(transforms);
}

// Restore canvas context update transformation stack
function _restoreCanvas(ctx, data) {
	if (data.savedTransforms.length === 0) {
		// Reset transformation state if it can't be restored any more
		data.transforms = _cloneTransforms(baseTransforms);
	} else {
		// Restore canvas context
		ctx.restore();
		// Restore current transform state to the last saved state
		data.transforms = data.savedTransforms.pop();
	}
}

// Set the style with the given name
function _setStyle(canvas, ctx, params, styleName) {
	if (params[styleName]) {
		if (isFunction(params[styleName])) {
			// Handle functions
			ctx[styleName] = params[styleName].call(canvas, params);
		} else {
			// Handle string values
			ctx[styleName] = params[styleName];
		}
	}
}

// Set canvas context properties
function _setGlobalProps(canvas, ctx, params) {
	_setStyle(canvas, ctx, params, 'fillStyle');
	_setStyle(canvas, ctx, params, 'strokeStyle');
	ctx.lineWidth = params.strokeWidth;
	// Optionally round corners for paths
	if (params.rounded) {
		ctx.lineCap = ctx.lineJoin = 'round';
	} else {
		ctx.lineCap = params.strokeCap;
		ctx.lineJoin = params.strokeJoin;
		ctx.miterLimit = params.miterLimit;
	}
	// Reset strokeDash if null
	if (!params.strokeDash) {
		params.strokeDash = [];
	}
	// Dashed lines
	if (ctx.setLineDash) {
		ctx.setLineDash(params.strokeDash);
	}
	ctx.webkitLineDash = params.strokeDash;
	ctx.lineDashOffset = ctx.webkitLineDashOffset = ctx.mozDashOffset = params.strokeDashOffset;
	// Drop shadow
	ctx.shadowOffsetX = params.shadowX;
	ctx.shadowOffsetY = params.shadowY;
	ctx.shadowBlur = params.shadowBlur;
	ctx.shadowColor = params.shadowColor;
	// Opacity and composite operation
	ctx.globalAlpha = params.opacity;
	ctx.globalCompositeOperation = params.compositing;
	// Support cross-browser toggling of image smoothing
	if (params.imageSmoothing) {
		ctx.imageSmoothingEnabled = params.imageSmoothing;
	}
}

// Optionally enable masking support for this path
function _enableMasking(ctx, data, params) {
	if (params.mask) {
		// If jCanvas autosave is enabled
		if (params.autosave) {
			// Automatically save transformation state by default
			_saveCanvas(ctx, data);
		}
		// Clip the current path
		ctx.clip();
		// Keep track of current masks
		data.transforms.masks.push(params._args);
	}
}

// Restore individual shape transformation
function _restoreTransform(ctx, params) {
	// If shape has been transformed by jCanvas
	if (params._transformed) {
		// Restore canvas context
		ctx.restore();
	}
}

// Close current canvas path
function _closePath(canvas, ctx, params) {
	var data;

	// Optionally close path
	if (params.closed) {
		ctx.closePath();
	}

	if (params.shadowStroke && params.strokeWidth !== 0) {
		// Extend the shadow to include the stroke of a drawing

		// Add a stroke shadow by stroking before filling
		ctx.stroke();
		ctx.fill();
		// Ensure the below stroking does not inherit a shadow
		ctx.shadowColor = 'transparent';
		ctx.shadowBlur = 0;
		// Stroke over fill as usual
		ctx.stroke();

	} else {
		// If shadowStroke is not enabled, stroke & fill as usual

		ctx.fill();
		// Prevent extra shadow created by stroke (but only when fill is present)
		if (params.fillStyle !== 'transparent') {
			ctx.shadowColor = 'transparent';
		}
		if (params.strokeWidth !== 0) {
			// Only stroke if the stroke is not 0
			ctx.stroke();
		}

	}

	// Optionally close path
	if (!params.closed) {
		ctx.closePath();
	}

	// Restore individual shape transformation
	_restoreTransform(ctx, params);

	// Mask shape if chosen
	if (params.mask) {
		// Retrieve canvas data
		data = _getCanvasData(canvas);
		_enableMasking(ctx, data, params);
	}

}

// Transform (translate, scale, or rotate) shape
function _transformShape(canvas, ctx, params, width, height) {

	// Get conversion factor for radians
	params._toRad = (params.inDegrees ? (PI / 180) : 1);

	params._transformed = true;
	ctx.save();

	// Optionally measure (x, y) position from top-left corner
	if (!params.fromCenter && !params._centered && width !== undefined) {
		// Always draw from center unless otherwise specified
		if (height === undefined) {
			height = width;
		}
		params.x += width / 2;
		params.y += height / 2;
		params._centered = true;
	}
	// Optionally rotate shape
	if (params.rotate) {
		_rotateCanvas(ctx, params, null);
	}
	// Optionally scale shape
	if (params.scale !== 1 || params.scaleX !== 1 || params.scaleY !== 1) {
		_scaleCanvas(ctx, params, null);
	}
	// Optionally translate shape
	if (params.translate || params.translateX || params.translateY) {
		_translateCanvas(ctx, params, null);
	}

}

/* Plugin API */

// Extend jCanvas with a user-defined method
jCanvas.extend = function extend(plugin) {

	// Create plugin
	if (plugin.name) {
		// Merge properties with defaults
		if (plugin.props) {
			extendObject(defaults, plugin.props);
		}
		// Define plugin method
		$.fn[plugin.name] = function self(args) {
			var $canvases = this, canvas, e, ctx,
				params;

			for (e = 0; e < $canvases.length; e += 1) {
				canvas = $canvases[e];
				ctx = _getContext(canvas);
				if (ctx) {

					params = new jCanvasObject(args);
					_addLayer(canvas, params, args, self);

					_setGlobalProps(canvas, ctx, params);
					plugin.fn.call(canvas, ctx, params);

				}
			}
			return $canvases;
		};
		// Add drawing type to drawing map
		if (plugin.type) {
			maps.drawings[plugin.type] = plugin.name;
		}
	}
	return $.fn[plugin.name];
};

/* Layer API */

// Retrieved the stored jCanvas data for a canvas element
function _getCanvasData(canvas) {
	var dataCache = caches.dataCache, data;
	if (dataCache._canvas === canvas && dataCache._data) {

		// Retrieve canvas data from cache if possible
		data = dataCache._data;

	} else {

		// Retrieve canvas data from jQuery's internal data storage
		data = $.data(canvas, 'jCanvas');
		if (!data) {

			// Create canvas data object if it does not already exist
			data = {
				// The associated canvas element
				canvas: canvas,
				// Layers array
				layers: [],
				// Layer maps
				layer: {
					names: {},
					groups: {}
				},
				eventHooks: {},
				// All layers that intersect with the event coordinates (regardless of visibility)
				intersecting: [],
				// The topmost layer whose area contains the event coordinates
				lastIntersected: null,
				cursor: $(canvas).css('cursor'),
				// Properties for the current drag event
				drag: {
					layer: null,
					dragging: false
				},
				// Data for the current event
				event: {
					type: null,
					x: null,
					y: null
				},
				// Events which already have been bound to the canvas
				events: {},
				// The canvas's current transformation state
				transforms: _cloneTransforms(baseTransforms),
				savedTransforms: [],
				// Whether a layer is being animated or not
				animating: false,
				// The layer currently being animated
				animated: null,
				// The device pixel ratio
				pixelRatio: 1,
				// Whether pixel ratio transformations have been applied
				scaled: false,
				// Whether the canvas should be redrawn when a layer mousemove
				// event triggers (either directly, or indirectly via dragging)
				redrawOnMousemove: false
			};
			// Use jQuery to store canvas data
			$.data(canvas, 'jCanvas', data);

		}
		// Cache canvas data for faster retrieval
		dataCache._canvas = canvas;
		dataCache._data = data;

	}
	return data;
}

// Initialize all of a layer's associated jCanvas events
function _addLayerEvents($canvas, data, layer) {
	var eventName;
	// Determine which jCanvas events need to be bound to this layer
	for (eventName in jCanvas.events) {
		if (Object.prototype.hasOwnProperty.call(jCanvas.events, eventName)) {
			// If layer has callback function to complement it
			if (layer[eventName] || (layer.cursors && layer.cursors[eventName])) {
				// Bind event to layer
				_addExplicitLayerEvent($canvas, data, layer, eventName);
			}
		}
	}
	if (!data.events.mouseout) {
		$canvas.bind('mouseout.jCanvas', function () {
			// Retrieve the layer whose drag event was canceled
			var layer = data.drag.layer, l;
			// If cursor mouses out of canvas while dragging
			if (layer) {
				// Cancel drag
				data.drag = {};
				_triggerLayerEvent($canvas, data, layer, 'dragcancel');
			}
			// Loop through all layers
			for (l = 0; l < data.layers.length; l += 1) {
				layer = data.layers[l];
				// If layer thinks it's still being moused over
				if (layer._hovered) {
					// Trigger mouseout on layer
					$canvas.triggerLayerEvent(data.layers[l], 'mouseout');
				}
			}
			// Redraw layers
			$canvas.drawLayers();
		});
		// Indicate that an event handler has been bound
		data.events.mouseout = true;
	}
}

// Initialize the given event on the given layer
function _addLayerEvent($canvas, data, layer, eventName) {
	// Use touch events if appropriate
	// eventName = _getMouseEventName(eventName);
	// Bind event to layer
	jCanvas.events[eventName]($canvas, data);
	layer._event = true;
}

// Add a layer event that was explicitly declared in the layer's parameter map,
// excluding events added implicitly (e.g. mousemove event required by draggable
// layers)
function _addExplicitLayerEvent($canvas, data, layer, eventName) {
	_addLayerEvent($canvas, data, layer, eventName);
	if (eventName === 'mouseover' || eventName === 'mouseout' || eventName === 'mousemove') {
		data.redrawOnMousemove = true;
	}
}

// Enable drag support for this layer
function _enableDrag($canvas, data, layer) {
	var dragHelperEvents, eventName, i;
	// Only make layer draggable if necessary
	if (layer.draggable || layer.cursors) {

		// Organize helper events which enable drag support
		dragHelperEvents = ['mousedown', 'mousemove', 'mouseup'];

		// Bind each helper event to the canvas
		for (i = 0; i < dragHelperEvents.length; i += 1) {
			// Use touch events if appropriate
			eventName = dragHelperEvents[i];
			// Bind event
			_addLayerEvent($canvas, data, layer, eventName);
		}
		// Indicate that this layer has events bound to it
		layer._event = true;

	}
}

// Update a layer property map if property is changed
function _updateLayerName($canvas, data, layer, props) {
	var nameMap = data.layer.names;

	// If layer name is being added, not changed
	if (!props) {

		props = layer;

	} else {

		// Remove old layer name entry because layer name has changed
		if (props.name !== undefined && isString(layer.name) && layer.name !== props.name) {
			delete nameMap[layer.name];
		}

	}

	// Add new entry to layer name map with new name
	if (isString(props.name)) {
		nameMap[props.name] = layer;
	}
}

// Create or update the data map for the given layer and group type
function _updateLayerGroups($canvas, data, layer, props) {
	var groupMap = data.layer.groups,
		group, groupName, g,
		index, l;

	// If group name is not changing
	if (!props) {

		props = layer;

	} else {

		// Remove layer from all of its associated groups
		if (props.groups !== undefined && layer.groups !== null) {
			for (g = 0; g < layer.groups.length; g += 1) {
				groupName = layer.groups[g];
				group = groupMap[groupName];
				if (group) {
					// Remove layer from its old layer group entry
					for (l = 0; l < group.length; l += 1) {
						if (group[l] === layer) {
							// Keep track of the layer's initial index
							index = l;
							// Remove layer once found
							group.splice(l, 1);
							break;
						}
					}
					// Remove layer group entry if group is empty
					if (group.length === 0) {
						delete groupMap[groupName];
					}
				}
			}
		}

	}

	// Add layer to new group if a new group name is given
	if (props.groups !== undefined && props.groups !== null) {

		for (g = 0; g < props.groups.length; g += 1) {

			groupName = props.groups[g];

			group = groupMap[groupName];
			if (!group) {
				// Create new group entry if it doesn't exist
				group = groupMap[groupName] = [];
				group.name = groupName;
			}
			if (index === undefined) {
				// Add layer to end of group unless otherwise stated
				index = group.length;
			}
			// Add layer to its new layer group
			group.splice(index, 0, layer);

		}

	}
}

// Get event hooks object for the first selected canvas
$.fn.getEventHooks = function getEventHooks() {
	var $canvases = this, canvas, data,
		eventHooks = {};

	if ($canvases.length !== 0) {
		canvas = $canvases[0];
		data = _getCanvasData(canvas);
		eventHooks = data.eventHooks;
	}
	return eventHooks;
};

// Set event hooks for the selected canvases
$.fn.setEventHooks = function setEventHooks(eventHooks) {
	var $canvases = this, e,
		data;
	for (e = 0; e < $canvases.length; e += 1) {
		data = _getCanvasData($canvases[e]);
		extendObject(data.eventHooks, eventHooks);
	}
	return $canvases;
};

// Get jCanvas layers array
$.fn.getLayers = function getLayers(callback) {
	var $canvases = this, canvas, data,
		layers, layer, l,
		matching = [];

	if ($canvases.length !== 0) {

		canvas = $canvases[0];
		data = _getCanvasData(canvas);
		// Retrieve layers array for this canvas
		layers = data.layers;

		// If a callback function is given
		if (isFunction(callback)) {

			// Filter the layers array using the callback
			for (l = 0; l < layers.length; l += 1) {
				layer = layers[l];
				if (callback.call(canvas, layer)) {
					// Add layer to array of matching layers if test passes
					matching.push(layer);
				}
			}

		} else {
			// Otherwise, get all layers

			matching = layers;

		}

	}
	return matching;
};

// Get a single jCanvas layer object
$.fn.getLayer = function getLayer(layerId) {
	var $canvases = this, canvas,
		data, layers, layer, l,
		idType;

	if ($canvases.length !== 0) {

		canvas = $canvases[0];
		data = _getCanvasData(canvas);
		layers = data.layers;
		idType = typeOf(layerId);

		if (layerId && layerId.layer) {

			// Return the actual layer object if given
			layer = layerId;

		} else if (idType === 'number') {

			// Retrieve the layer using the given index

			// Allow for negative indices
			if (layerId < 0) {
				layerId = layers.length + layerId;
			}
			// Get layer with the given index
			layer = layers[layerId];

		} else if (idType === 'regexp') {

			// Get layer with the name that matches the given regex
			for (l = 0; l < layers.length; l += 1) {
				// Check if layer matches name
				if (isString(layers[l].name) && layers[l].name.match(layerId)) {
					layer = layers[l];
					break;
				}
			}

		} else {

			// Get layer with the given name
			layer = data.layer.names[layerId];

		}

	}
	return layer;
};

// Get all layers in the given group
$.fn.getLayerGroup = function getLayerGroup(groupId) {
	var $canvases = this, canvas, data,
		groups, groupName, group,
		idType = typeOf(groupId);

	if ($canvases.length !== 0) {

		canvas = $canvases[0];

		if (idType === 'array') {

			// Return layer group if given
			group = groupId;

		} else if (idType === 'regexp') {

			// Get canvas data
			data = _getCanvasData(canvas);
			groups = data.layer.groups;
			// Loop through all layers groups for this canvas
			for (groupName in groups) {
				// Find a group whose name matches the given regex
				if (groupName.match(groupId)) {
					group = groups[groupName];
					// Stop after finding the first matching group
					break;
				}
			}

		} else {

			// Find layer group with the given group name
			data = _getCanvasData(canvas);
			group = data.layer.groups[groupId];
		}

	}
	return group;
};

// Get index of layer in layers array
$.fn.getLayerIndex = function getLayerIndex(layerId) {
	var $canvases = this,
		layers = $canvases.getLayers(),
		layer = $canvases.getLayer(layerId);

	return inArray(layer, layers);
};

// Set properties of a layer
$.fn.setLayer = function setLayer(layerId, props) {
	var $canvases = this, $canvas, e,
		data, layer,
		propName, propValue, propType;

	for (e = 0; e < $canvases.length; e += 1) {
		$canvas = $($canvases[e]);
		data = _getCanvasData($canvases[e]);

		layer = $($canvases[e]).getLayer(layerId);
		if (layer) {

			// Update layer property maps
			_updateLayerName($canvas, data, layer, props);
			_updateLayerGroups($canvas, data, layer, props);

			_coerceNumericProps(props);

			// Merge properties with layer
			for (propName in props) {
				if (Object.prototype.hasOwnProperty.call(props, propName)) {
					propValue = props[propName];
					propType = typeOf(propValue);
					if (propType === 'object' && isPlainObject(propValue)) {
						// Clone objects
						layer[propName] = extendObject({}, propValue);
						_coerceNumericProps(layer[propName]);
					} else if (propType === 'array') {
						// Clone arrays
						layer[propName] = propValue.slice(0);
					} else if (propType === 'string') {
						if (propValue.indexOf('+=') === 0) {
							// Increment numbers prefixed with +=
							layer[propName] += parseFloat(propValue.substr(2));
						} else if (propValue.indexOf('-=') === 0) {
							// Decrement numbers prefixed with -=
							layer[propName] -= parseFloat(propValue.substr(2));
						} else if (!isNaN(propValue) && isNumeric(propValue) && propName !== 'text') {
							// Convert numeric values as strings to numbers
							layer[propName] = parseFloat(propValue);
						} else {
							// Otherwise, set given string value
							layer[propName] = propValue;
						}
					} else {
						// Otherwise, set given value
						layer[propName] = propValue;
					}
				}
			}

			// Update layer events
			_addLayerEvents($canvas, data, layer);
			_enableDrag($canvas, data, layer);

			// If layer's properties were changed
			if ($.isEmptyObject(props) === false) {
				_triggerLayerEvent($canvas, data, layer, 'change', props);
			}

		}
	}
	return $canvases;
};

// Set properties of all layers (optionally filtered by a callback)
$.fn.setLayers = function setLayers(props, callback) {
	var $canvases = this, $canvas, e,
		layers, l;
	for (e = 0; e < $canvases.length; e += 1) {
		$canvas = $($canvases[e]);

		layers = $canvas.getLayers(callback);
		// Loop through all layers
		for (l = 0; l < layers.length; l += 1) {
			// Set properties of each layer
			$canvas.setLayer(layers[l], props);
		}
	}
	return $canvases;
};

// Set properties of all layers in the given group
$.fn.setLayerGroup = function setLayerGroup(groupId, props) {
	var $canvases = this, $canvas, e,
		group, l;

	for (e = 0; e < $canvases.length; e += 1) {
		// Get layer group
		$canvas = $($canvases[e]);

		group = $canvas.getLayerGroup(groupId);
		// If group exists
		if (group) {

			// Loop through layers in group
			for (l = 0; l < group.length; l += 1) {
				// Merge given properties with layer
				$canvas.setLayer(group[l], props);
			}

		}
	}
	return $canvases;
};

// Move a layer to the given index in the layers array
$.fn.moveLayer = function moveLayer(layerId, index) {
	var $canvases = this, $canvas, e,
		data, layers, layer;

	for (e = 0; e < $canvases.length; e += 1) {
		$canvas = $($canvases[e]);
		data = _getCanvasData($canvases[e]);

		// Retrieve layers array and desired layer
		layers = data.layers;
		layer = $canvas.getLayer(layerId);
		if (layer) {

			// Ensure layer index is accurate
			layer.index = inArray(layer, layers);

			// Remove layer from its current placement
			layers.splice(layer.index, 1);
			// Add layer in its new placement
			layers.splice(index, 0, layer);

			// Handle negative indices
			if (index < 0) {
				index = layers.length + index;
			}
			// Update layer's stored index
			layer.index = index;

			_triggerLayerEvent($canvas, data, layer, 'move');

		}
	}
	return $canvases;
};

// Remove a jCanvas layer
$.fn.removeLayer = function removeLayer(layerId) {
	var $canvases = this, $canvas, e, data,
		layers, layer;

	for (e = 0; e < $canvases.length; e += 1) {
		$canvas = $($canvases[e]);
		data = _getCanvasData($canvases[e]);

		// Retrieve layers array and desired layer
		layers = $canvas.getLayers();
		layer = $canvas.getLayer(layerId);
		// Remove layer if found
		if (layer) {

			// Ensure layer index is accurate
			layer.index = inArray(layer, layers);
			// Remove layer and allow it to be re-added later
			layers.splice(layer.index, 1);
			delete layer._layer;

			// Update layer name map
			_updateLayerName($canvas, data, layer, {
				name: null
			});
			// Update layer group map
			_updateLayerGroups($canvas, data, layer, {
				groups: null
			});

			// Trigger 'remove' event
			_triggerLayerEvent($canvas, data, layer, 'remove');

		}
	}
	return $canvases;
};

// Remove all layers
$.fn.removeLayers = function removeLayers(callback) {
	var $canvases = this, $canvas, e,
		data, layers, layer, l;

	for (e = 0; e < $canvases.length; e += 1) {
		$canvas = $($canvases[e]);
		data = _getCanvasData($canvases[e]);
		layers = $canvas.getLayers(callback);
		// Remove all layers individually
		for (l = 0; l < layers.length; l += 1) {
			layer = layers[l];
			$canvas.removeLayer(layer);
			// Ensure no layer is skipped over
			l -= 1;
		}
		// Update layer maps
		data.layer.names = {};
		data.layer.groups = {};
	}
	return $canvases;
};

// Remove all layers in the group with the given ID
$.fn.removeLayerGroup = function removeLayerGroup(groupId) {
	var $canvases = this, $canvas, e, group, l;

	if (groupId !== undefined) {
		for (e = 0; e < $canvases.length; e += 1) {
			$canvas = $($canvases[e]);

			group = $canvas.getLayerGroup(groupId);
			// Remove layer group using given group name
			if (group) {

				// Clone groups array
				group = group.slice(0);

				// Loop through layers in group
				for (l = 0; l < group.length; l += 1) {
					$canvas.removeLayer(group[l]);
				}

			}
		}
	}
	return $canvases;
};

// Add an existing layer to a layer group
$.fn.addLayerToGroup = function addLayerToGroup(layerId, groupName) {
	var $canvases = this, $canvas, e,
		layer, groups = [groupName];

	for (e = 0; e < $canvases.length; e += 1) {
		$canvas = $($canvases[e]);
		layer = $canvas.getLayer(layerId);

		// If layer is not already in group
		if (layer.groups) {
			// Clone groups list
			groups = layer.groups.slice(0);
			// If layer is not already in group
			if (inArray(groupName, layer.groups) === -1) {
				// Add layer to group
				groups.push(groupName);
			}
		}
		// Update layer group maps
		$canvas.setLayer(layer, {
			groups: groups
		});

	}
	return $canvases;
};

// Remove an existing layer from a layer group
$.fn.removeLayerFromGroup = function removeLayerFromGroup(layerId, groupName) {
	var $canvases = this, $canvas, e,
		layer, groups = [],
		index;

	for (e = 0; e < $canvases.length; e += 1) {
		$canvas = $($canvases[e]);
		layer = $canvas.getLayer(layerId);

		if (layer.groups) {

			// Find index of layer in group
			index = inArray(groupName, layer.groups);

			// If layer is in group
			if (index !== -1) {

				// Clone groups list
				groups = layer.groups.slice(0);

				// Remove layer from group
				groups.splice(index, 1);

				// Update layer group maps
				$canvas.setLayer(layer, {
					groups: groups
				});

			}

		}

	}
	return $canvases;
};

// Get topmost layer that intersects with event coordinates
function _getIntersectingLayer(data) {
	var layer, i,
		mask, m;

	// Store the topmost layer
	layer = null;

	// Get the topmost layer whose visible area intersects event coordinates
	for (i = data.intersecting.length - 1; i >= 0; i -= 1) {

		// Get current layer
		layer = data.intersecting[i];

		// If layer has previous masks
		if (layer._masks) {

			// Search previous masks to ensure
			// layer is visible at event coordinates
			for (m = layer._masks.length - 1; m >= 0; m -= 1) {
				mask = layer._masks[m];
				// If mask does not intersect event coordinates
				if (!mask.intersects) {
					// Indicate that the mask does not
					// intersect event coordinates
					layer.intersects = false;
					// Stop searching previous masks
					break;
				}

			}

			// If event coordinates intersect all previous masks
			// and layer is not intangible
			if (layer.intersects && !layer.intangible) {
				// Stop searching for topmost layer
				break;
			}

		}

	}
	// If resulting layer is intangible
	if (layer && layer.intangible) {
		// Cursor does not intersect this layer
		layer = null;
	}
	return layer;
}

// Draw individual layer (internal)
function _drawLayer($canvas, ctx, layer, nextLayerIndex) {
	if (layer && layer.visible && layer._method) {
		if (nextLayerIndex) {
			layer._next = nextLayerIndex;
		} else {
			layer._next = null;
		}
		// If layer is an object, call its respective method
		if (layer._method) {
			layer._method.call($canvas, layer);
		}
	}
}

// Handle dragging of the currently-dragged layer
function _handleLayerDrag($canvas, data, eventType) {
	var layers, layer, l,
		drag, dragGroups,
		group, groupName, g,
		newX, newY;

	drag = data.drag;
	layer = drag.layer;
	dragGroups = (layer && layer.dragGroups) || [];
	layers = data.layers;

	if (eventType === 'mousemove' || eventType === 'touchmove') {
		// Detect when user is currently dragging layer

		if (!drag.dragging) {
			// Detect when user starts dragging layer

			// Signify that a layer on the canvas is being dragged
			drag.dragging = true;
			layer.dragging = true;

			// Optionally bring layer to front when drag starts
			if (layer.bringToFront) {
				// Remove layer from its original position
				layers.splice(layer.index, 1);
				// Bring layer to front
				// push() returns the new array length
				layer.index = layers.push(layer);
			}

			// Set drag properties for this layer
			layer._startX = layer.x;
			layer._startY = layer.y;
			layer._endX = layer._eventX;
			layer._endY = layer._eventY;

			// Trigger dragstart event
			_triggerLayerEvent($canvas, data, layer, 'dragstart');

		}

		if (drag.dragging) {

			// Calculate position after drag
			newX = layer._eventX - (layer._endX - layer._startX);
			newY = layer._eventY - (layer._endY - layer._startY);
			if (layer.updateDragX) {
				newX = layer.updateDragX.call($canvas[0], layer, newX);
			}
			if (layer.updateDragY) {
				newY = layer.updateDragY.call($canvas[0], layer, newY);
			}
			layer.dx = newX - layer.x;
			layer.dy = newY - layer.y;
			if (layer.restrictDragToAxis !== 'y') {
				layer.x = newX;
			}
			if (layer.restrictDragToAxis !== 'x') {
				layer.y = newY;
			}

			// Trigger drag event
			_triggerLayerEvent($canvas, data, layer, 'drag');

			// Move groups with layer on drag
			for (g = 0; g < dragGroups.length; g += 1) {

				groupName = dragGroups[g];
				group = data.layer.groups[groupName];
				if (layer.groups && group) {

					for (l = 0; l < group.length; l += 1) {
						if (group[l] !== layer) {
							if (layer.restrictDragToAxis !== 'y' && group[l].restrictDragToAxis !== 'y') {
								group[l].x += layer.dx;
							}
							if (layer.restrictDragToAxis !== 'x' && group[l].restrictDragToAxis !== 'x') {
								group[l].y += layer.dy;
							}
						}
					}

				}

			}

		}

	} else if (eventType === 'mouseup' || eventType === 'touchend') {
		// Detect when user stops dragging layer

		if (drag.dragging) {
			layer.dragging = false;
			drag.dragging = false;
			data.redrawOnMousemove = data.originalRedrawOnMousemove;
			// Trigger dragstop event
			_triggerLayerEvent($canvas, data, layer, 'dragstop');
		}

		// Cancel dragging
		data.drag = {};

	}
}


// List of CSS3 cursors that need to be prefixed
css.cursors = ['grab', 'grabbing', 'zoom-in', 'zoom-out'];

// Function to detect vendor prefix
// Modified version of David Walsh's implementation
// https://davidwalsh.name/vendor-prefix
css.prefix = (function () {
	var styles = getComputedStyle(document.documentElement, ''),
		pre = (arraySlice
			.call(styles)
			.join('')
			.match(/-(moz|webkit|ms)-/) || (styles.OLink === '' && ['', 'o'])
		)[1];
	return '-' + pre + '-';
})();

// Set cursor on canvas
function _setCursor($canvas, layer, eventType) {
	var cursor;
	if (layer.cursors) {
		// Retrieve cursor from cursors object if it exists
		cursor = layer.cursors[eventType];
	}
	// Prefix any CSS3 cursor
	if ($.inArray(cursor, css.cursors) !== -1) {
		cursor = css.prefix + cursor;
	}
	// If cursor is defined
	if (cursor) {
		// Set canvas cursor
		$canvas.css({
			cursor: cursor
		});
	}
}

// Reset cursor on canvas
function _resetCursor($canvas, data) {
	$canvas.css({
		cursor: data.cursor
	});
}

// Run the given event callback with the given arguments
function _runEventCallback($canvas, layer, eventType, callbacks, arg) {
	// Prevent callback from firing recursively
	if (callbacks[eventType] && layer._running && !layer._running[eventType]) {
		// Signify the start of callback execution for this event
		layer._running[eventType] = true;
		// Run event callback with the given arguments
		callbacks[eventType].call($canvas[0], layer, arg);
		// Signify the end of callback execution for this event
		layer._running[eventType] = false;
	}
}

// Determine if the given layer can "legally" fire the given event
function _layerCanFireEvent(layer, eventType) {
	// If events are disable and if
	// layer is tangible or event is not tangible
	return (!layer.disableEvents &&
		(!layer.intangible || $.inArray(eventType, tangibleEvents) === -1));
}

// Trigger the given event on the given layer
function _triggerLayerEvent($canvas, data, layer, eventType, arg) {
	// If layer can legally fire this event type
	if (_layerCanFireEvent(layer, eventType)) {

		// Do not set a custom cursor on layer mouseout
		if (eventType !== 'mouseout') {
			// Update cursor if one is defined for this event
			_setCursor($canvas, layer, eventType);
		}

		// Trigger the user-defined event callback
		_runEventCallback($canvas, layer, eventType, layer, arg);
		// Trigger the canvas-bound event hook
		_runEventCallback($canvas, layer, eventType, data.eventHooks, arg);
		// Trigger the global event hook
		_runEventCallback($canvas, layer, eventType, jCanvas.eventHooks, arg);

	}
}

// Manually trigger a layer event
$.fn.triggerLayerEvent = function (layer, eventType) {
	var $canvases = this, $canvas, e,
		data;

	for (e = 0; e < $canvases.length; e += 1) {
		$canvas = $($canvases[e]);
		data = _getCanvasData($canvases[e]);
		layer = $canvas.getLayer(layer);
		if (layer) {
			_triggerLayerEvent($canvas, data, layer, eventType);
		}
	}
	return $canvases;
};

// Draw layer with the given ID
$.fn.drawLayer = function drawLayer(layerId) {
	var $canvases = this, e, ctx,
		$canvas, layer;

	for (e = 0; e < $canvases.length; e += 1) {
		$canvas = $($canvases[e]);
		ctx = _getContext($canvases[e]);
		if (ctx) {
			layer = $canvas.getLayer(layerId);
			_drawLayer($canvas, ctx, layer);
		}
	}
	return $canvases;
};

// Draw all layers (or, if given, only layers starting at an index)
$.fn.drawLayers = function drawLayers(args) {
	var $canvases = this, $canvas, e, ctx,
		// Internal parameters for redrawing the canvas
		params = args || {},
		// Other variables
		layers, layer, lastLayer, l, index, lastIndex,
		data, eventCache, eventType, isImageLayer;

	// The layer index from which to start redrawing the canvas
	index = params.index;
	if (!index) {
		index = 0;
	}

	for (e = 0; e < $canvases.length; e += 1) {
		$canvas = $($canvases[e]);
		ctx = _getContext($canvases[e]);
		if (ctx) {

			data = _getCanvasData($canvases[e]);

			// Clear canvas first unless otherwise directed
			if (params.clear !== false) {
				$canvas.clearCanvas();
			}

			// Cache the layers array
			layers = data.layers;

			// Draw layers from first to last (bottom to top)
			for (l = index; l < layers.length; l += 1) {
				layer = layers[l];

				// Ensure layer index is up-to-date
				layer.index = l;

				// Prevent any one event from firing excessively
				if (params.resetFire) {
					layer._fired = false;
				}
				// Draw layer
				_drawLayer($canvas, ctx, layer, l + 1);
				// Store list of previous masks for each layer
				layer._masks = data.transforms.masks.slice(0);

				// Allow image layers to load before drawing successive layers
				if (layer._method === $.fn.drawImage && layer.visible) {
					isImageLayer = true;
					break;
				}

			}

			// If layer is an image layer
			if (isImageLayer) {
				// Stop and wait for drawImage() to resume drawLayers()
				break;
			}

			// Store the latest
			lastIndex = l;

			// Get first layer that intersects with event coordinates
			layer = _getIntersectingLayer(data);

			eventCache = data.event;
			eventType = eventCache.type;

			// If jCanvas has detected a dragstart
			if (data.drag.layer) {
				// Handle dragging of layer
				_handleLayerDrag($canvas, data, eventType);
			}

			// Manage mouseout event
			lastLayer = data.lastIntersected;
			if (lastLayer !== null && layer !== lastLayer && lastLayer._hovered && !lastLayer._fired && !data.drag.dragging) {

				data.lastIntersected = null;
				lastLayer._fired = true;
				lastLayer._hovered = false;
				_triggerLayerEvent($canvas, data, lastLayer, 'mouseout');
				_resetCursor($canvas, data);

			}

			if (layer) {

				// Use mouse event callbacks if no touch event callbacks are given
				if (!layer[eventType]) {
					eventType = _getMouseEventName(eventType);
				}

				// Check events for intersecting layer
				if (layer._event && layer.intersects) {

					data.lastIntersected = layer;

					// Detect mouseover events
					if ((layer.mouseover || layer.mouseout || layer.cursors) && !data.drag.dragging) {

						if (!layer._hovered && !layer._fired) {

							// Prevent events from firing excessively
							layer._fired = true;
							layer._hovered = true;
							_triggerLayerEvent($canvas, data, layer, 'mouseover');

						}

					}

					// Detect any other mouse event
					if (!layer._fired) {

						// Prevent event from firing twice unintentionally
						layer._fired = true;
						eventCache.type = null;

						_triggerLayerEvent($canvas, data, layer, eventType);

					}

					// Use the mousedown event to start drag
					if (layer.draggable && !layer.disableEvents && (eventType === 'mousedown' || eventType === 'touchstart')) {

						// Keep track of drag state
						data.drag.layer = layer;
						data.originalRedrawOnMousemove = data.redrawOnMousemove;
						data.redrawOnMousemove = true;

					}

				}

			}

			// If cursor is not intersecting with any layer
			if (layer === null && !data.drag.dragging) {
				// Reset cursor to previous state
				_resetCursor($canvas, data);
			}

			// If the last layer has been drawn
			if (lastIndex === layers.length) {

				// Reset list of intersecting layers
				data.intersecting.length = 0;
				// Reset transformation stack
				data.transforms = _cloneTransforms(baseTransforms);
				data.savedTransforms.length = 0;

			}

		}
	}
	return $canvases;
};

// Add a jCanvas layer (internal)
function _addLayer(canvas, params, args, method) {
	var $canvas, data,
		layers, layer = (params._layer ? args : params);

	// Store arguments object for later use
	params._args = args;

	// Convert all draggable drawings into jCanvas layers
	if (params.draggable || params.dragGroups) {
		params.layer = true;
		params.draggable = true;
	}

	// Determine the layer's type using the available information
	if (!params._method) {
		if (method) {
			params._method = method;
		} else if (params.method) {
			params._method = $.fn[params.method];
		} else if (params.type) {
			params._method = $.fn[maps.drawings[params.type]];
		}
	}

	// If layer hasn't been added yet
	if (params.layer && !params._layer) {
		// Add layer to canvas

		$canvas = $(canvas);

		data = _getCanvasData(canvas);
		layers = data.layers;

		// Do not add duplicate layers of same name
		if (layer.name === null || (isString(layer.name) && data.layer.names[layer.name] === undefined)) {

			// Convert number properties to numbers
			_coerceNumericProps(params);

			// Ensure layers are unique across canvases by cloning them
			layer = new jCanvasObject(params);
			layer.canvas = canvas;
			// Indicate that this is a layer for future checks
			layer.layer = true;
			layer._layer = true;
			layer._running = {};
			// If layer stores user-defined data
			if (layer.data !== null) {
				// Clone object
				layer.data = extendObject({}, layer.data);
			} else {
				// Otherwise, create data object
				layer.data = {};
			}
			// If layer stores a list of associated groups
			if (layer.groups !== null) {
				// Clone list
				layer.groups = layer.groups.slice(0);
			} else {
				// Otherwise, create empty list
				layer.groups = [];
			}

			// Update layer group maps
			_updateLayerName($canvas, data, layer);
			_updateLayerGroups($canvas, data, layer);

			// Check for any associated jCanvas events and enable them
			_addLayerEvents($canvas, data, layer);

			// Optionally enable drag-and-drop support and cursor support
			_enableDrag($canvas, data, layer);

			// Copy _event property to parameters object
			params._event = layer._event;

			// Calculate width/height for text layers
			if (layer._method === $.fn.drawText) {
				$canvas.measureText(layer);
			}

			// Add layer to end of array if no index is specified
			if (layer.index === null) {
				layer.index = layers.length;
			}

			// Add layer to layers array at specified index
			layers.splice(layer.index, 0, layer);

			// Store layer on parameters object
			params._args = layer;

			// Trigger an 'add' event
			_triggerLayerEvent($canvas, data, layer, 'add');

		}

	} else if (!params.layer) {
		_coerceNumericProps(params);
	}

	return layer;
}

// Add a jCanvas layer
$.fn.addLayer = function addLayer(args) {
	var $canvases = this, e, ctx,
		params;

	for (e = 0; e < $canvases.length; e += 1) {
		ctx = _getContext($canvases[e]);
		if (ctx) {

			params = new jCanvasObject(args);
			params.layer = true;
			_addLayer($canvases[e], params, args);

		}
	}
	return $canvases;
};

/* Animation API */

// Define properties used in both CSS and jCanvas
css.props = [
	'width',
	'height',
	'opacity',
	'lineHeight'
];
css.propsObj = {};

// Hide/show jCanvas/CSS properties so they can be animated using jQuery
function _showProps(obj) {
	var cssProp, p;
	for (p = 0; p < css.props.length; p += 1) {
		cssProp = css.props[p];
		obj[cssProp] = obj['_' + cssProp];
	}
}
function _hideProps(obj, reset) {
	var cssProp, p;
	for (p = 0; p < css.props.length; p += 1) {
		cssProp = css.props[p];
		// Hide property using same name with leading underscore
		if (obj[cssProp] !== undefined) {
			obj['_' + cssProp] = obj[cssProp];
			css.propsObj[cssProp] = true;
			if (reset) {
				delete obj[cssProp];
			}
		}
	}
}

// Evaluate property values that are functions
function _parseEndValues(canvas, layer, endValues) {
	var propName, propValue,
		subPropName, subPropValue;
	// Loop through all properties in map of end values
	for (propName in endValues) {
		if (Object.prototype.hasOwnProperty.call(endValues, propName)) {
			propValue = endValues[propName];
			// If end value is function
			if (isFunction(propValue)) {
				// Call function and use its value as the end value
				endValues[propName] = propValue.call(canvas, layer, propName);
			}
			// If end value is an object
			if (typeOf(propValue) === 'object' && isPlainObject(propValue)) {
				// Prepare to animate properties in object
				for (subPropName in propValue) {
					if (Object.prototype.hasOwnProperty.call(propValue, subPropName)) {
						subPropValue = propValue[subPropName];
						// Store property's start value at top-level of layer
						if (layer[propName] !== undefined) {
							layer[propName + '.' + subPropName] = layer[propName][subPropName];
							// Store property's end value at top-level of end values map
							endValues[propName + '.' + subPropName] = subPropValue;
						}
					}
				}
				// Delete sub-property of object as it's no longer needed
				delete endValues[propName];
			}
		}
	}
	return endValues;
}

// Remove sub-property aliases from layer object
function _removeSubPropAliases(layer) {
	var propName;
	for (propName in layer) {
		if (Object.prototype.hasOwnProperty.call(layer, propName)) {
			if (propName.indexOf('.') !== -1) {
				delete layer[propName];
			}
		}
	}
}

// Convert a color value to an array of RGB values
function _colorToRgbArray(color) {
	var originalColor, elem,
		rgb = [],
		multiple = 1;

	// Deal with complete transparency
	if (color === 'transparent') {
		color = 'rgba(0, 0, 0, 0)';
	} else if (color.match(/^([a-z]+|#[0-9a-f]+)$/gi)) {
		// Deal with hexadecimal colors and color names
		elem = document.head;
		originalColor = elem.style.color;
		elem.style.color = color;
		color = $.css(elem, 'color');
		elem.style.color = originalColor;
	}
	// Parse RGB string
	if (color.match(/^rgb/gi)) {
		rgb = color.match(/(\d+(\.\d+)?)/gi);
		// Deal with RGB percentages
		if (color.match(/%/gi)) {
			multiple = 2.55;
		}
		rgb[0] *= multiple;
		rgb[1] *= multiple;
		rgb[2] *= multiple;
		// Ad alpha channel if given
		if (rgb[3] !== undefined) {
			rgb[3] = parseFloat(rgb[3]);
		} else {
			rgb[3] = 1;
		}
	}
	return rgb;
}

// Animate a hex or RGB color
function _animateColor(fx) {
	var n = 3,
		i;
	// Only parse start and end colors once
	if (typeOf(fx.start) !== 'array') {
		fx.start = _colorToRgbArray(fx.start);
		fx.end = _colorToRgbArray(fx.end);
	}
	fx.now = [];

	// If colors are RGBA, animate transparency
	if (fx.start[3] !== 1 || fx.end[3] !== 1) {
		n = 4;
	}

	// Calculate current frame for red, green, blue, and alpha
	for (i = 0; i < n; i += 1) {
		fx.now[i] = fx.start[i] + ((fx.end[i] - fx.start[i]) * fx.pos);
		// Only the red, green, and blue values must be integers
		if (i < 3) {
			fx.now[i] = round(fx.now[i]);
		}
	}
	if (fx.start[3] !== 1 || fx.end[3] !== 1) {
		// Only use RGBA if RGBA colors are given
		fx.now = 'rgba(' + fx.now.join(',') + ')';
	} else {
		// Otherwise, animate as solid colors
		fx.now.slice(0, 3);
		fx.now = 'rgb(' + fx.now.join(',') + ')';
	}
	// Animate colors for both canvas layers and DOM elements
	if (fx.elem.nodeName) {
		fx.elem.style[fx.prop] = fx.now;
	} else {
		fx.elem[fx.prop] = fx.now;
	}
}

// Animate jCanvas layer
$.fn.animateLayer = function animateLayer() {
	var $canvases = this, $canvas, e, ctx,
		args = arraySlice.call(arguments, 0),
		data, layer, props;

	// Deal with all cases of argument placement
	/*
		0. layer name/index
		1. properties
		2. duration/options
		3. easing
		4. complete function
		5. step function
	*/

	if (typeOf(args[2]) === 'object') {

		// Accept an options object for animation
		args.splice(2, 0, args[2].duration || null);
		args.splice(3, 0, args[3].easing || null);
		args.splice(4, 0, args[4].complete || null);
		args.splice(5, 0, args[5].step || null);

	} else {

		if (args[2] === undefined) {
			// If object is the last argument
			args.splice(2, 0, null);
			args.splice(3, 0, null);
			args.splice(4, 0, null);
		} else if (isFunction(args[2])) {
			// If callback comes after object
			args.splice(2, 0, null);
			args.splice(3, 0, null);
		}
		if (args[3] === undefined) {
			// If duration is the last argument
			args[3] = null;
			args.splice(4, 0, null);
		} else if (isFunction(args[3])) {
			// If callback comes after duration
			args.splice(3, 0, null);
		}

	}

	// Run callback function when animation completes
	function complete($canvas, data, layer) {

		return function () {

			_showProps(layer);
			_removeSubPropAliases(layer);

			// Prevent multiple redraw loops
			if (!data.animating || data.animated === layer) {
				// Redraw layers on last frame
				$canvas.drawLayers();
			}

			// Signify the end of an animation loop
			layer._animating = false;
			data.animating = false;
			data.animated = null;

			// If callback is defined
			if (args[4]) {
				// Run callback at the end of the animation
				args[4].call($canvas[0], layer);
			}

			_triggerLayerEvent($canvas, data, layer, 'animateend');

		};

	}

	// Redraw layers on every frame of the animation
	function step($canvas, data, layer) {

		return function (now, fx) {
			var parts, propName, subPropName,
				hidden = false;

			// If animated property has been hidden
			if (fx.prop[0] === '_') {
				hidden = true;
				// Unhide property temporarily
				fx.prop = fx.prop.replace('_', '');
				layer[fx.prop] = layer['_' + fx.prop];
			}

			// If animating property of sub-object
			if (fx.prop.indexOf('.') !== -1) {
				parts = fx.prop.split('.');
				propName = parts[0];
				subPropName = parts[1];
				if (layer[propName]) {
					layer[propName][subPropName] = fx.now;
				}
			}

			// Throttle animation to improve efficiency
			if (layer._pos !== fx.pos) {

				layer._pos = fx.pos;

				// Signify the start of an animation loop
				if (!layer._animating && !data.animating) {
					layer._animating = true;
					data.animating = true;
					data.animated = layer;
				}

				// Prevent multiple redraw loops
				if (!data.animating || data.animated === layer) {
					// Redraw layers for every frame
					$canvas.drawLayers();
				}

			}

			// If callback is defined
			if (args[5]) {
				// Run callback for each step of animation
				args[5].call($canvas[0], now, fx, layer);
			}

			_triggerLayerEvent($canvas, data, layer, 'animate', fx);

			// If property should be hidden during animation
			if (hidden) {
				// Hide property again
				fx.prop = '_' + fx.prop;
			}

		};

	}

	for (e = 0; e < $canvases.length; e += 1) {
		$canvas = $($canvases[e]);
		ctx = _getContext($canvases[e]);
		if (ctx) {

			data = _getCanvasData($canvases[e]);

			// If a layer object was passed, use it the layer to be animated
			layer = $canvas.getLayer(args[0]);

			// Ignore layers that are functions
			if (layer && layer._method !== $.fn.draw) {

				// Do not modify original object
				props = extendObject({}, args[1]);

				props = _parseEndValues($canvases[e], layer, props);

				// Bypass jQuery CSS Hooks for CSS properties (width, opacity, etc.)
				_hideProps(props, true);
				_hideProps(layer);

				// Fix for jQuery's vendor prefixing support, which affects how width/height/opacity are animated
				layer.style = css.propsObj;

				// Animate layer
				$(layer).animate(props, {
					duration: args[2],
					easing: ($.easing[args[3]] ? args[3] : null),
					// When animation completes
					complete: complete($canvas, data, layer),
					// Redraw canvas for every animation frame
					step: step($canvas, data, layer)
				});
				_triggerLayerEvent($canvas, data, layer, 'animatestart');
			}

		}
	}
	return $canvases;
};

// Animate all layers in a layer group
$.fn.animateLayerGroup = function animateLayerGroup(groupId) {
	var $canvases = this, $canvas, e,
		args = arraySlice.call(arguments, 0),
		group, l;
	for (e = 0; e < $canvases.length; e += 1) {
		$canvas = $($canvases[e]);
		group = $canvas.getLayerGroup(groupId);
		if (group) {

			// Animate all layers in the group
			for (l = 0; l < group.length; l += 1) {

				// Replace first argument with layer
				args[0] = group[l];
				$canvas.animateLayer.apply($canvas, args);

			}

		}
	}
	return $canvases;
};

// Delay layer animation by a given number of milliseconds
$.fn.delayLayer = function delayLayer(layerId, duration) {
	var $canvases = this, $canvas, e,
		data, layer;
	duration = duration || 0;

	for (e = 0; e < $canvases.length; e += 1) {
		$canvas = $($canvases[e]);
		data = _getCanvasData($canvases[e]);
		layer = $canvas.getLayer(layerId);
		// If layer exists
		if (layer) {
			// Delay animation
			$(layer).delay(duration);
			_triggerLayerEvent($canvas, data, layer, 'delay');
		}
	}
	return $canvases;
};

// Delay animation all layers in a layer group
$.fn.delayLayerGroup = function delayLayerGroup(groupId, duration) {
	var $canvases = this, $canvas, e,
		group, layer, l;
	duration = duration || 0;

	for (e = 0; e < $canvases.length; e += 1) {
		$canvas = $($canvases[e]);

		group = $canvas.getLayerGroup(groupId);
		// Delay all layers in the group
		if (group) {

			for (l = 0; l < group.length; l += 1) {
				// Delay each layer in the group
				layer = group[l];
				$canvas.delayLayer(layer, duration);
			}

		}
	}
	return $canvases;
};

// Stop layer animation
$.fn.stopLayer = function stopLayer(layerId, clearQueue) {
	var $canvases = this, $canvas, e,
		data, layer;

	for (e = 0; e < $canvases.length; e += 1) {
		$canvas = $($canvases[e]);
		data = _getCanvasData($canvases[e]);
		layer = $canvas.getLayer(layerId);
		// If layer exists
		if (layer) {
			// Stop animation
			$(layer).stop(clearQueue);
			_triggerLayerEvent($canvas, data, layer, 'stop');
		}
	}
	return $canvases;
};

// Stop animation of all layers in a layer group
$.fn.stopLayerGroup = function stopLayerGroup(groupId, clearQueue) {
	var $canvases = this, $canvas, e,
		group, layer, l;

	for (e = 0; e < $canvases.length; e += 1) {
		$canvas = $($canvases[e]);

		group = $canvas.getLayerGroup(groupId);
		// Stop all layers in the group
		if (group) {

			for (l = 0; l < group.length; l += 1) {
				// Stop each layer in the group
				layer = group[l];
				$canvas.stopLayer(layer, clearQueue);
			}

		}
	}
	return $canvases;
};

// Enable animation for color properties
function _supportColorProps(props) {
	var p;
	for (p = 0; p < props.length; p += 1) {
		$.fx.step[props[p]] = _animateColor;
	}
}

// Enable animation for color properties
_supportColorProps([
	'color',
	'backgroundColor',
	'borderColor',
	'borderTopColor',
	'borderRightColor',
	'borderBottomColor',
	'borderLeftColor',
	'fillStyle',
	'outlineColor',
	'strokeStyle',
	'shadowColor'
]);

/* Event API */

// Map standard mouse events to touch events
maps.touchEvents = {
	'mousedown': 'touchstart',
	'mouseup': 'touchend',
	'mousemove': 'touchmove'
};
// Map standard touch events to mouse events
maps.mouseEvents = {
	'touchstart': 'mousedown',
	'touchend': 'mouseup',
	'touchmove': 'mousemove'
};

// Convert mouse event name to a corresponding touch event name (if possible)
function _getTouchEventName(eventName) {
	// Detect touch event support
	if (maps.touchEvents[eventName]) {
		eventName = maps.touchEvents[eventName];
	}
	return eventName;
}
// Convert touch event name to a corresponding mouse event name
function _getMouseEventName(eventName) {
	if (maps.mouseEvents[eventName]) {
		eventName = maps.mouseEvents[eventName];
	}
	return eventName;
}

// Bind event to jCanvas layer using standard jQuery events
function _createEvent(eventName) {

	jCanvas.events[eventName] = function ($canvas, data) {
		var helperEventName, touchEventName, eventCache;

		// Retrieve canvas's event cache
		eventCache = data.event;

		// Both mouseover/mouseout events will be managed by a single mousemove event
		helperEventName = (eventName === 'mouseover' || eventName === 'mouseout') ? 'mousemove' : eventName;
		touchEventName = _getTouchEventName(helperEventName);

		function eventCallback(event) {
			// Cache current mouse position and redraw layers
			eventCache.x = event.offsetX;
			eventCache.y = event.offsetY;
			eventCache.type = helperEventName;
			eventCache.event = event;
			// Redraw layers on every trigger of the event; don't redraw if at
			// least one layer is draggable and there are no layers with
			// explicit mouseover/mouseout/mousemove events
			if (event.type !== 'mousemove' || data.redrawOnMousemove || data.drag.dragging) {
				$canvas.drawLayers({
					resetFire: true
				});
			}
			// Prevent default event behavior
			event.preventDefault();
		}

		// Ensure the event is not bound more than once
		if (!data.events[helperEventName]) {
			// Bind one canvas event which handles all layer events of that type
			if (touchEventName !== helperEventName) {
				$canvas.bind(helperEventName + '.jCanvas ' + touchEventName + '.jCanvas', eventCallback);
			} else {
				$canvas.bind(helperEventName + '.jCanvas', eventCallback);
			}
			// Prevent this event from being bound twice
			data.events[helperEventName] = true;
		}
	};
}
function _createEvents(eventNames) {
	var n;
	for (n = 0; n < eventNames.length; n += 1) {
		_createEvent(eventNames[n]);
	}
}
// Populate jCanvas events object with some standard events
_createEvents([
	'click',
	'dblclick',
	'mousedown',
	'mouseup',
	'mousemove',
	'mouseover',
	'mouseout',
	'touchstart',
	'touchmove',
	'touchend',
	'pointerdown',
	'pointermove',
	'pointerup',
	'contextmenu'
]);

// Check if event fires when a drawing is drawn
function _detectEvents(canvas, ctx, params) {
	var layer, data, eventCache, intersects,
		transforms, x, y, angle;

	// Use the layer object stored by the given parameters object
	layer = params._args;
	// Canvas must have event bindings
	if (layer) {

		data = _getCanvasData(canvas);
		eventCache = data.event;
		if (eventCache.x !== null && eventCache.y !== null) {
			// Respect user-defined pixel ratio
			x = eventCache.x * data.pixelRatio;
			y = eventCache.y * data.pixelRatio;
			// Determine if the given coordinates are in the current path
			intersects = ctx.isPointInPath(x, y) || (ctx.isPointInStroke && ctx.isPointInStroke(x, y));
		}
		transforms = data.transforms;

		// Allow callback functions to retrieve the mouse coordinates
		layer.eventX = eventCache.x;
		layer.eventY = eventCache.y;
		layer.event = eventCache.event;

		// Adjust coordinates to match current canvas transformation

		// Keep track of some transformation values
		angle = data.transforms.rotate;
		x = layer.eventX;
		y = layer.eventY;

		if (angle !== 0) {
			// Rotate coordinates if coordinate space has been rotated
			layer._eventX = (x * cos(-angle)) - (y * sin(-angle));
			layer._eventY = (y * cos(-angle)) + (x * sin(-angle));
		} else {
			// Otherwise, no calculations need to be made
			layer._eventX = x;
			layer._eventY = y;
		}

		// Scale coordinates
		layer._eventX /= transforms.scaleX;
		layer._eventY /= transforms.scaleY;

		// If layer intersects with cursor
		if (intersects) {
			// Add it to a list of layers that intersect with cursor
			data.intersecting.push(layer);
		}
		layer.intersects = Boolean(intersects);
	}
}

// Normalize offsetX and offsetY for all browsers
$.event.fix = function (event) {
	var offset, originalEvent, touches;

	event = jQueryEventFix.call($.event, event);
	originalEvent = event.originalEvent;

	// originalEvent does not exist for manually-triggered events
	if (originalEvent) {

		touches = originalEvent.changedTouches;

		// If offsetX and offsetY are not supported, define them
		if (event.pageX !== undefined && event.offsetX === undefined) {
			try {
				offset = $(event.currentTarget).offset();
				if (offset) {
					event.offsetX = event.pageX - offset.left;
					event.offsetY = event.pageY - offset.top;
				}
			} catch (error) {
				// Fail silently
			}
		} else if (touches) {
			try {
				// Enable offsetX and offsetY for mobile devices
				offset = $(event.currentTarget).offset();
				if (offset) {
					event.offsetX = touches[0].pageX - offset.left;
					event.offsetY = touches[0].pageY - offset.top;
				}
			} catch (error) {
				// Fail silently
			}
		}

	}
	return event;
};

/* Drawing API */

// Map drawing names with their respective method names
maps.drawings = {
	'arc': 'drawArc',
	'bezier': 'drawBezier',
	'ellipse': 'drawEllipse',
	'function': 'draw',
	'image': 'drawImage',
	'line': 'drawLine',
	'path': 'drawPath',
	'polygon': 'drawPolygon',
	'slice': 'drawSlice',
	'quadratic': 'drawQuadratic',
	'rectangle': 'drawRect',
	'text': 'drawText',
	'vector': 'drawVector',
	'save': 'saveCanvas',
	'restore': 'restoreCanvas',
	'rotate': 'rotateCanvas',
	'scale': 'scaleCanvas',
	'translate': 'translateCanvas'
};

// Draws on canvas using a function
$.fn.draw = function draw(args) {
	var $canvases = this, e, ctx,
		params = new jCanvasObject(args);

	// Draw using any other method
	if (maps.drawings[params.type] && params.type !== 'function') {

		$canvases[maps.drawings[params.type]](args);

	} else {

		for (e = 0; e < $canvases.length; e += 1) {
			ctx = _getContext($canvases[e]);
			if (ctx) {

				params = new jCanvasObject(args);
				_addLayer($canvases[e], params, args, draw);
				if (params.visible) {

					if (params.fn) {
						// Call the given user-defined function
						params.fn.call($canvases[e], ctx, params);
					}

				}

			}
		}

	}
	return $canvases;
};

// Clears canvas
$.fn.clearCanvas = function clearCanvas(args) {
	var $canvases = this, e, ctx,
		params = new jCanvasObject(args);

	for (e = 0; e < $canvases.length; e += 1) {
		ctx = _getContext($canvases[e]);
		if (ctx) {

			if (params.width === null || params.height === null) {
				// Clear entire canvas if width/height is not given

				// Reset current transformation temporarily to ensure that the entire canvas is cleared
				ctx.save();
				ctx.setTransform(1, 0, 0, 1, 0, 0);
				ctx.clearRect(0, 0, $canvases[e].width, $canvases[e].height);
				ctx.restore();

			} else {
				// Otherwise, clear the defined section of the canvas

				// Transform clear rectangle
				_addLayer($canvases[e], params, args, clearCanvas);
				_transformShape($canvases[e], ctx, params, params.width, params.height);
				ctx.clearRect(params.x - (params.width / 2), params.y - (params.height / 2), params.width, params.height);
				// Restore previous transformation
				_restoreTransform(ctx, params);

			}

		}
	}
	return $canvases;
};

/* Transformation API */

// Restores canvas
$.fn.saveCanvas = function saveCanvas(args) {
	var $canvases = this, e, ctx,
		params, data, i;

	for (e = 0; e < $canvases.length; e += 1) {
		ctx = _getContext($canvases[e]);
		if (ctx) {

			data = _getCanvasData($canvases[e]);

			params = new jCanvasObject(args);
			_addLayer($canvases[e], params, args, saveCanvas);

			// Restore a number of times using the given count
			for (i = 0; i < params.count; i += 1) {
				_saveCanvas(ctx, data);
			}

		}
	}
	return $canvases;
};

// Restores canvas
$.fn.restoreCanvas = function restoreCanvas(args) {
	var $canvases = this, e, ctx,
		params, data, i;

	for (e = 0; e < $canvases.length; e += 1) {
		ctx = _getContext($canvases[e]);
		if (ctx) {

			data = _getCanvasData($canvases[e]);

			params = new jCanvasObject(args);
			_addLayer($canvases[e], params, args, restoreCanvas);

			// Restore a number of times using the given count
			for (i = 0; i < params.count; i += 1) {
				_restoreCanvas(ctx, data);
			}

		}
	}
	return $canvases;
};

// Rotates canvas (internal)
function _rotateCanvas(ctx, params, transforms) {

	// Get conversion factor for radians
	params._toRad = (params.inDegrees ? (PI / 180) : 1);

	// Rotate canvas using shape as center of rotation
	ctx.translate(params.x, params.y);
	ctx.rotate(params.rotate * params._toRad);
	ctx.translate(-params.x, -params.y);

	// If transformation data was given
	if (transforms) {
		// Update transformation data
		transforms.rotate += (params.rotate * params._toRad);
	}
}

// Scales canvas (internal)
function _scaleCanvas(ctx, params, transforms) {

	// Scale both the x- and y- axis using the 'scale' property
	if (params.scale !== 1) {
		params.scaleX = params.scaleY = params.scale;
	}

	// Scale canvas using shape as center of rotation
	ctx.translate(params.x, params.y);
	ctx.scale(params.scaleX, params.scaleY);
	ctx.translate(-params.x, -params.y);

	// If transformation data was given
	if (transforms) {
		// Update transformation data
		transforms.scaleX *= params.scaleX;
		transforms.scaleY *= params.scaleY;
	}
}

// Translates canvas (internal)
function _translateCanvas(ctx, params, transforms) {

	// Translate both the x- and y-axis using the 'translate' property
	if (params.translate) {
		params.translateX = params.translateY = params.translate;
	}

	// Translate canvas
	ctx.translate(params.translateX, params.translateY);

	// If transformation data was given
	if (transforms) {
		// Update transformation data
		transforms.translateX += params.translateX;
		transforms.translateY += params.translateY;
	}
}

// Rotates canvas
$.fn.rotateCanvas = function rotateCanvas(args) {
	var $canvases = this, e, ctx,
		params, data;

	for (e = 0; e < $canvases.length; e += 1) {
		ctx = _getContext($canvases[e]);
		if (ctx) {

			data = _getCanvasData($canvases[e]);

			params = new jCanvasObject(args);
			_addLayer($canvases[e], params, args, rotateCanvas);

			// Autosave transformation state by default
			if (params.autosave) {
				// Automatically save transformation state by default
				_saveCanvas(ctx, data);
			}
			_rotateCanvas(ctx, params, data.transforms);
		}

	}
	return $canvases;
};

// Scales canvas
$.fn.scaleCanvas = function scaleCanvas(args) {
	var $canvases = this, e, ctx,
		params, data;

	for (e = 0; e < $canvases.length; e += 1) {
		ctx = _getContext($canvases[e]);
		if (ctx) {

			data = _getCanvasData($canvases[e]);

			params = new jCanvasObject(args);
			_addLayer($canvases[e], params, args, scaleCanvas);

			// Autosave transformation state by default
			if (params.autosave) {
				// Automatically save transformation state by default
				_saveCanvas(ctx, data);
			}
			_scaleCanvas(ctx, params, data.transforms);

		}
	}
	return $canvases;
};

// Translates canvas
$.fn.translateCanvas = function translateCanvas(args) {
	var $canvases = this, e, ctx,
		params, data;

	for (e = 0; e < $canvases.length; e += 1) {
		ctx = _getContext($canvases[e]);
		if (ctx) {

			data = _getCanvasData($canvases[e]);

			params = new jCanvasObject(args);
			_addLayer($canvases[e], params, args, translateCanvas);

			// Autosave transformation state by default
			if (params.autosave) {
				// Automatically save transformation state by default
				_saveCanvas(ctx, data);
			}
			_translateCanvas(ctx, params, data.transforms);

		}
	}
	return $canvases;
};

/* Shape API */

// Draws rectangle
$.fn.drawRect = function drawRect(args) {
	var $canvases = this, e, ctx,
		params,
		x1, y1,
		x2, y2,
		r, temp;

	for (e = 0; e < $canvases.length; e += 1) {
		ctx = _getContext($canvases[e]);
		if (ctx) {

			params = new jCanvasObject(args);
			_addLayer($canvases[e], params, args, drawRect);
			if (params.visible) {

				_transformShape($canvases[e], ctx, params, params.width, params.height);
				_setGlobalProps($canvases[e], ctx, params);

				ctx.beginPath();
				if (params.width && params.height) {
					x1 = params.x - (params.width / 2);
					y1 = params.y - (params.height / 2);
					r = abs(params.cornerRadius);
					// If corner radius is defined and is not zero
					if (r) {
						// Draw rectangle with rounded corners if cornerRadius is defined

						x2 = params.x + (params.width / 2);
						y2 = params.y + (params.height / 2);

						// Handle negative width
						if (params.width < 0) {
							temp = x1;
							x1 = x2;
							x2 = temp;
						}
						// Handle negative height
						if (params.height < 0) {
							temp = y1;
							y1 = y2;
							y2 = temp;
						}

						// Prevent over-rounded corners
						if ((x2 - x1) - (2 * r) < 0) {
							r = (x2 - x1) / 2;
						}
						if ((y2 - y1) - (2 * r) < 0) {
							r = (y2 - y1) / 2;
						}

						// Draw rectangle
						ctx.moveTo(x1 + r, y1);
						ctx.lineTo(x2 - r, y1);
						ctx.arc(x2 - r, y1 + r, r, 3 * PI / 2, PI * 2, false);
						ctx.lineTo(x2, y2 - r);
						ctx.arc(x2 - r, y2 - r, r, 0, PI / 2, false);
						ctx.lineTo(x1 + r, y2);
						ctx.arc(x1 + r, y2 - r, r, PI / 2, PI, false);
						ctx.lineTo(x1, y1 + r);
						ctx.arc(x1 + r, y1 + r, r, PI, 3 * PI / 2, false);
						// Always close path
						params.closed = true;

					} else {

						// Otherwise, draw rectangle with square corners
						ctx.rect(x1, y1, params.width, params.height);

					}
				}
				// Check for jCanvas events
				_detectEvents($canvases[e], ctx, params);
				// Close rectangle path
				_closePath($canvases[e], ctx, params);
			}
		}
	}
	return $canvases;
};

// Retrieves a coterminal angle between 0 and 2pi for the given angle
function _getCoterminal(angle) {
	while (angle < 0) {
		angle += (2 * PI);
	}
	return angle;
}

// Retrieves the x-coordinate for the given angle in a circle
function _getArcX(params, angle) {
	return params.x + (params.radius * cos(angle));
}
// Retrieves the y-coordinate for the given angle in a circle
function _getArcY(params, angle) {
	return params.y + (params.radius * sin(angle));
}

// Draws arc (internal)
function _drawArc(canvas, ctx, params, path) {
	var x1, y1, x2, y2,
		x3, y3, x4, y4,
		offsetX, offsetY,
		diff;

	// Determine offset from dragging
	if (params === path) {
		offsetX = 0;
		offsetY = 0;
	} else {
		offsetX = params.x;
		offsetY = params.y;
	}

	// Convert default end angle to radians
	if (!path.inDegrees && path.end === 360) {
		path.end = PI * 2;
	}

	// Convert angles to radians
	path.start *= params._toRad;
	path.end *= params._toRad;
	// Consider 0deg due north of arc
	path.start -= (PI / 2);
	path.end -= (PI / 2);

	// Ensure arrows are pointed correctly for CCW arcs
	diff = PI / 180;
	if (path.ccw) {
		diff *= -1;
	}

	// Calculate coordinates for start arrow
	x1 = _getArcX(path, path.start + diff);
	y1 = _getArcY(path, path.start + diff);
	x2 = _getArcX(path, path.start);
	y2 = _getArcY(path, path.start);

	_addStartArrow(
		canvas, ctx,
		params, path,
		x1, y1,
		x2, y2
	);

	// Draw arc
	ctx.arc(path.x + offsetX, path.y + offsetY, path.radius, path.start, path.end, path.ccw);

	// Calculate coordinates for end arrow
	x3 = _getArcX(path, path.end + diff);
	y3 = _getArcY(path, path.end + diff);
	x4 = _getArcX(path, path.end);
	y4 = _getArcY(path, path.end);

	_addEndArrow(
		canvas, ctx,
		params, path,
		x4, y4,
		x3, y3
	);
}

// Draws arc or circle
$.fn.drawArc = function drawArc(args) {
	var $canvases = this, e, ctx,
		params;

	for (e = 0; e < $canvases.length; e += 1) {
		ctx = _getContext($canvases[e]);
		if (ctx) {

			params = new jCanvasObject(args);
			_addLayer($canvases[e], params, args, drawArc);
			if (params.visible) {

				_transformShape($canvases[e], ctx, params, params.radius * 2);
				_setGlobalProps($canvases[e], ctx, params);

				ctx.beginPath();
				_drawArc($canvases[e], ctx, params, params);
				// Check for jCanvas events
				_detectEvents($canvases[e], ctx, params);
				// Optionally close path
				_closePath($canvases[e], ctx, params);

			}

		}
	}
	return $canvases;
};

// Draws ellipse
$.fn.drawEllipse = function drawEllipse(args) {
	var $canvases = this, e, ctx,
		params,
		controlW,
		controlH;

	for (e = 0; e < $canvases.length; e += 1) {
		ctx = _getContext($canvases[e]);
		if (ctx) {

			params = new jCanvasObject(args);
			_addLayer($canvases[e], params, args, drawEllipse);
			if (params.visible) {

				_transformShape($canvases[e], ctx, params, params.width, params.height);
				_setGlobalProps($canvases[e], ctx, params);

				// Calculate control width and height
				controlW = params.width * (4 / 3);
				controlH = params.height;

				// Create ellipse using curves
				ctx.beginPath();
				ctx.moveTo(params.x, params.y - (controlH / 2));
				// Left side
				ctx.bezierCurveTo(params.x - (controlW / 2), params.y - (controlH / 2), params.x - (controlW / 2), params.y + (controlH / 2), params.x, params.y + (controlH / 2));
				// Right side
				ctx.bezierCurveTo(params.x + (controlW / 2), params.y + (controlH / 2), params.x + (controlW / 2), params.y - (controlH / 2), params.x, params.y - (controlH / 2));
				// Check for jCanvas events
				_detectEvents($canvases[e], ctx, params);
				// Always close path
				params.closed = true;
				_closePath($canvases[e], ctx, params);

			}
		}
	}
	return $canvases;
};

// Draws a regular (equal-angled) polygon
$.fn.drawPolygon = function drawPolygon(args) {
	var $canvases = this, e, ctx,
		params,
		theta, dtheta, hdtheta,
		apothem,
		x, y, i;

	for (e = 0; e < $canvases.length; e += 1) {
		ctx = _getContext($canvases[e]);
		if (ctx) {

			params = new jCanvasObject(args);
			_addLayer($canvases[e], params, args, drawPolygon);
			if (params.visible) {

				_transformShape($canvases[e], ctx, params, params.radius * 2);
				_setGlobalProps($canvases[e], ctx, params);

				// Polygon's central angle
				dtheta = (2 * PI) / params.sides;
				// Half of dtheta
				hdtheta = dtheta / 2;
				// Polygon's starting angle
				theta = hdtheta + (PI / 2);
				// Distance from polygon's center to the middle of its side
				apothem = params.radius * cos(hdtheta);

				// Calculate path and draw
				ctx.beginPath();
				for (i = 0; i < params.sides; i += 1) {

					// Draw side of polygon
					x = params.x + (params.radius * cos(theta));
					y = params.y + (params.radius * sin(theta));

					// Plot point on polygon
					ctx.lineTo(x, y);

					// Project side if chosen
					if (params.concavity) {
						// Sides are projected from the polygon's apothem
						x = params.x + ((apothem + (-apothem * params.concavity)) * cos(theta + hdtheta));
						y = params.y + ((apothem + (-apothem * params.concavity)) * sin(theta + hdtheta));
						ctx.lineTo(x, y);
					}

					// Increment theta by delta theta
					theta += dtheta;

				}
				// Check for jCanvas events
				_detectEvents($canvases[e], ctx, params);
				// Always close path
				params.closed = true;
				_closePath($canvases[e], ctx, params);

			}
		}
	}
	return $canvases;
};

// Draws pie-shaped slice
$.fn.drawSlice = function drawSlice(args) {
	var $canvases = this, e, ctx,
		params,
		angle, dx, dy;

	for (e = 0; e < $canvases.length; e += 1) {
		ctx = _getContext($canvases[e]);
		if (ctx) {

			params = new jCanvasObject(args);
			_addLayer($canvases[e], params, args, drawSlice);
			if (params.visible) {

				_transformShape($canvases[e], ctx, params, params.radius * 2);
				_setGlobalProps($canvases[e], ctx, params);

				// Perform extra calculations

				// Convert angles to radians
				params.start *= params._toRad;
				params.end *= params._toRad;
				// Consider 0deg at north of arc
				params.start -= (PI / 2);
				params.end -= (PI / 2);

				// Find positive equivalents of angles
				params.start = _getCoterminal(params.start);
				params.end = _getCoterminal(params.end);
				// Ensure start angle is less than end angle
				if (params.end < params.start) {
					params.end += (2 * PI);
				}

				// Calculate angular position of slice
				angle = ((params.start + params.end) / 2);

				// Calculate ratios for slice's angle
				dx = (params.radius * params.spread * cos(angle));
				dy = (params.radius * params.spread * sin(angle));

				// Adjust position of slice
				params.x += dx;
				params.y += dy;

				// Draw slice
				ctx.beginPath();
				ctx.arc(params.x, params.y, params.radius, params.start, params.end, params.ccw);
				ctx.lineTo(params.x, params.y);
				// Check for jCanvas events
				_detectEvents($canvases[e], ctx, params);
				// Always close path
				params.closed = true;
				_closePath($canvases[e], ctx, params);

			}

		}
	}
	return $canvases;
};

/* Path API */

// Adds arrow to path using the given properties
function _addArrow(canvas, ctx, params, path, x1, y1, x2, y2) {
	var leftX, leftY,
		rightX, rightY,
		offsetX, offsetY,
		angle;

	// If arrow radius is given and path is not closed
	if (path.arrowRadius && !params.closed) {

		// Calculate angle
		angle = atan2((y2 - y1), (x2 - x1));
		// Adjust angle correctly
		angle -= PI;
		// Calculate offset to place arrow at edge of path
		offsetX = (params.strokeWidth * cos(angle));
		offsetY = (params.strokeWidth * sin(angle));

		// Calculate coordinates for left half of arrow
		leftX = x2 + (path.arrowRadius * cos(angle + (path.arrowAngle / 2)));
		leftY = y2 + (path.arrowRadius * sin(angle + (path.arrowAngle / 2)));
		// Calculate coordinates for right half of arrow
		rightX = x2 + (path.arrowRadius * cos(angle - (path.arrowAngle / 2)));
		rightY = y2 + (path.arrowRadius * sin(angle - (path.arrowAngle / 2)));

		// Draw left half of arrow
		ctx.moveTo(leftX - offsetX, leftY - offsetY);
		ctx.lineTo(x2 - offsetX, y2 - offsetY);
		// Draw right half of arrow
		ctx.lineTo(rightX - offsetX, rightY - offsetY);

		// Visually connect arrow to path
		ctx.moveTo(x2 - offsetX, y2 - offsetY);
		ctx.lineTo(x2 + offsetX, y2 + offsetY);
		// Move back to end of path
		ctx.moveTo(x2, y2);

	}
}

// Optionally adds arrow to start of path
function _addStartArrow(canvas, ctx, params, path, x1, y1, x2, y2) {
	if (!path._arrowAngleConverted) {
		path.arrowAngle *= params._toRad;
		path._arrowAngleConverted = true;
	}
	if (path.startArrow) {
		_addArrow(canvas, ctx, params, path, x1, y1, x2, y2);
	}
}

// Optionally adds arrow to end of path
function _addEndArrow(canvas, ctx, params, path, x1, y1, x2, y2) {
	if (!path._arrowAngleConverted) {
		path.arrowAngle *= params._toRad;
		path._arrowAngleConverted = true;
	}
	if (path.endArrow) {
		_addArrow(canvas, ctx, params, path, x1, y1, x2, y2);
	}
}

// Draws line (internal)
function _drawLine(canvas, ctx, params, path) {
	var l,
		lx, ly;
	l = 2;
	_addStartArrow(
		canvas, ctx,
		params, path,
		path.x2 + params.x,
		path.y2 + params.y,
		path.x1 + params.x,
		path.y1 + params.y
	);
	if (path.x1 !== undefined && path.y1 !== undefined) {
		ctx.moveTo(path.x1 + params.x, path.y1 + params.y);
	}
	while (true) {
		// Calculate next coordinates
		lx = path['x' + l];
		ly = path['y' + l];
		// If coordinates are given
		if (lx !== undefined && ly !== undefined) {
			// Draw next line
			ctx.lineTo(lx + params.x, ly + params.y);
			l += 1;
		} else {
			// Otherwise, stop drawing
			break;
		}
	}
	l -= 1;
	// Optionally add arrows to path
	_addEndArrow(
		canvas, ctx,
		params,
		path,
		path['x' + (l - 1)] + params.x,
		path['y' + (l - 1)] + params.y,
		path['x' + l] + params.x,
		path['y' + l] + params.y
	);
}

// Draws line
$.fn.drawLine = function drawLine(args) {
	var $canvases = this, e, ctx,
		params;

	for (e = 0; e < $canvases.length; e += 1) {
		ctx = _getContext($canvases[e]);
		if (ctx) {

			params = new jCanvasObject(args);
			_addLayer($canvases[e], params, args, drawLine);
			if (params.visible) {

				_transformShape($canvases[e], ctx, params);
				_setGlobalProps($canvases[e], ctx, params);

				// Draw each point
				ctx.beginPath();
				_drawLine($canvases[e], ctx, params, params);
				// Check for jCanvas events
				_detectEvents($canvases[e], ctx, params);
				// Optionally close path
				_closePath($canvases[e], ctx, params);

			}

		}
	}
	return $canvases;
};

// Draws quadratic curve (internal)
function _drawQuadratic(canvas, ctx, params, path) {
	var l,
		lx, ly,
		lcx, lcy;

	l = 2;

	_addStartArrow(
		canvas,
		ctx,
		params,
		path,
		path.cx1 + params.x,
		path.cy1 + params.y,
		path.x1 + params.x,
		path.y1 + params.y
	);

	if (path.x1 !== undefined && path.y1 !== undefined) {
		ctx.moveTo(path.x1 + params.x, path.y1 + params.y);
	}
	while (true) {
		// Calculate next coordinates
		lx = path['x' + l];
		ly = path['y' + l];
		lcx = path['cx' + (l - 1)];
		lcy = path['cy' + (l - 1)];
		// If coordinates are given
		if (lx !== undefined && ly !== undefined && lcx !== undefined && lcy !== undefined) {
			// Draw next curve
			ctx.quadraticCurveTo(lcx + params.x, lcy + params.y, lx + params.x, ly + params.y);
			l += 1;
		} else {
			// Otherwise, stop drawing
			break;
		}
	}
	l -= 1;
	_addEndArrow(
		canvas,
		ctx,
		params,
		path,
		path['cx' + (l - 1)] + params.x,
		path['cy' + (l - 1)] + params.y,
		path['x' + l] + params.x,
		path['y' + l] + params.y
	);
}

// Draws quadratic curve
$.fn.drawQuadratic = function drawQuadratic(args) {
	var $canvases = this, e, ctx,
		params;

	for (e = 0; e < $canvases.length; e += 1) {
		ctx = _getContext($canvases[e]);
		if (ctx) {

			params = new jCanvasObject(args);
			_addLayer($canvases[e], params, args, drawQuadratic);
			if (params.visible) {

				_transformShape($canvases[e], ctx, params);
				_setGlobalProps($canvases[e], ctx, params);

				// Draw each point
				ctx.beginPath();
				_drawQuadratic($canvases[e], ctx, params, params);
				// Check for jCanvas events
				_detectEvents($canvases[e], ctx, params);
				// Optionally close path
				_closePath($canvases[e], ctx, params);

			}
		}
	}
	return $canvases;
};

// Draws Bezier curve (internal)
function _drawBezier(canvas, ctx, params, path) {
	var l, lc,
		lx, ly,
		lcx1, lcy1,
		lcx2, lcy2;

	l = 2;
	lc = 1;

	_addStartArrow(
		canvas,
		ctx,
		params,
		path,
		path.cx1 + params.x,
		path.cy1 + params.y,
		path.x1 + params.x,
		path.y1 + params.y
	);

	if (path.x1 !== undefined && path.y1 !== undefined) {
		ctx.moveTo(path.x1 + params.x, path.y1 + params.y);
	}
	while (true) {
		// Calculate next coordinates
		lx = path['x' + l];
		ly = path['y' + l];
		lcx1 = path['cx' + lc];
		lcy1 = path['cy' + lc];
		lcx2 = path['cx' + (lc + 1)];
		lcy2 = path['cy' + (lc + 1)];
		// If next coordinates are given
		if (lx !== undefined && ly !== undefined && lcx1 !== undefined && lcy1 !== undefined && lcx2 !== undefined && lcy2 !== undefined) {
			// Draw next curve
			ctx.bezierCurveTo(lcx1 + params.x, lcy1 + params.y, lcx2 + params.x, lcy2 + params.y, lx + params.x, ly + params.y);
			l += 1;
			lc += 2;
		} else {
			// Otherwise, stop drawing
			break;
		}
	}
	l -= 1;
	lc -= 2;
	_addEndArrow(
		canvas,
		ctx,
		params,
		path,
		path['cx' + (lc + 1)] + params.x,
		path['cy' + (lc + 1)] + params.y,
		path['x' + l] + params.x,
		path['y' + l] + params.y
	);
}

// Draws Bezier curve
$.fn.drawBezier = function drawBezier(args) {
	var $canvases = this, e, ctx,
		params;

	for (e = 0; e < $canvases.length; e += 1) {
		ctx = _getContext($canvases[e]);
		if (ctx) {

			params = new jCanvasObject(args);
			_addLayer($canvases[e], params, args, drawBezier);
			if (params.visible) {

				_transformShape($canvases[e], ctx, params);
				_setGlobalProps($canvases[e], ctx, params);

				// Draw each point
				ctx.beginPath();
				_drawBezier($canvases[e], ctx, params, params);
				// Check for jCanvas events
				_detectEvents($canvases[e], ctx, params);
				// Optionally close path
				_closePath($canvases[e], ctx, params);

			}
		}
	}
	return $canvases;
};

// Retrieves the x-coordinate for the given vector angle and length
function _getVectorX(params, angle, length) {
	angle *= params._toRad;
	angle -= (PI / 2);
	return (length * cos(angle));
}
// Retrieves the y-coordinate for the given vector angle and length
function _getVectorY(params, angle, length) {
	angle *= params._toRad;
	angle -= (PI / 2);
	return (length * sin(angle));
}

// Draws vector (internal) #2
function _drawVector(canvas, ctx, params, path) {
	var l, angle, length,
		offsetX, offsetY,
		x, y,
		x3, y3,
		x4, y4;

	// Determine offset from dragging
	if (params === path) {
		offsetX = 0;
		offsetY = 0;
	} else {
		offsetX = params.x;
		offsetY = params.y;
	}

	l = 1;
	x = x3 = x4 = path.x + offsetX;
	y = y3 = y4 = path.y + offsetY;

	_addStartArrow(
		canvas, ctx,
		params, path,
		x + _getVectorX(params, path.a1, path.l1),
		y + _getVectorY(params, path.a1, path.l1),
		x,
		y
	);

	// The vector starts at the given (x, y) coordinates
	if (path.x !== undefined && path.y !== undefined) {
		ctx.moveTo(x, y);
	}
	while (true) {

		angle = path['a' + l];
		length = path['l' + l];

		if (angle !== undefined && length !== undefined) {
			// Convert the angle to radians with 0 degrees starting at north
			// Keep track of last two coordinates
			x3 = x4;
			y3 = y4;
			// Compute (x, y) coordinates from angle and length
			x4 += _getVectorX(params, angle, length);
			y4 += _getVectorY(params, angle, length);
			ctx.lineTo(x4, y4);
			l += 1;
		} else {
			// Otherwise, stop drawing
			break;
		}

	}
	_addEndArrow(
		canvas, ctx,
		params, path,
		x3, y3,
		x4, y4
	);
}

// Draws vector
$.fn.drawVector = function drawVector(args) {
	var $canvases = this, e, ctx,
		params;

	for (e = 0; e < $canvases.length; e += 1) {
		ctx = _getContext($canvases[e]);
		if (ctx) {

			params = new jCanvasObject(args);
			_addLayer($canvases[e], params, args, drawVector);
			if (params.visible) {

				_transformShape($canvases[e], ctx, params);
				_setGlobalProps($canvases[e], ctx, params);

				// Draw each point
				ctx.beginPath();
				_drawVector($canvases[e], ctx, params, params);
				// Check for jCanvas events
				_detectEvents($canvases[e], ctx, params);
				// Optionally close path
				_closePath($canvases[e], ctx, params);

			}
		}
	}
	return $canvases;
};

// Draws a path consisting of one or more subpaths
$.fn.drawPath = function drawPath(args) {
	var $canvases = this, e, ctx,
		params,
		l, lp;

	for (e = 0; e < $canvases.length; e += 1) {
		ctx = _getContext($canvases[e]);
		if (ctx) {

			params = new jCanvasObject(args);
			_addLayer($canvases[e], params, args, drawPath);
			if (params.visible) {

				_transformShape($canvases[e], ctx, params);
				_setGlobalProps($canvases[e], ctx, params);

				ctx.beginPath();
				l = 1;
				while (true) {
					lp = params['p' + l];
					if (lp !== undefined) {
						lp = new jCanvasObject(lp);
						if (lp.type === 'line') {
							_drawLine($canvases[e], ctx, params, lp);
						} else if (lp.type === 'quadratic') {
							_drawQuadratic($canvases[e], ctx, params, lp);
						} else if (lp.type === 'bezier') {
							_drawBezier($canvases[e], ctx, params, lp);
						} else if (lp.type === 'vector') {
							_drawVector($canvases[e], ctx, params, lp);
						} else if (lp.type === 'arc') {
							_drawArc($canvases[e], ctx, params, lp);
						}
						l += 1;
					} else {
						break;
					}
				}

				// Check for jCanvas events
				_detectEvents($canvases[e], ctx, params);
				// Optionally close path
				_closePath($canvases[e], ctx, params);

			}

		}
	}
	return $canvases;
};

/* Text API */

// Calculates font string and set it as the canvas font
function _setCanvasFont(canvas, ctx, params) {
	// Otherwise, use the given font attributes
	if (!isNaN(Number(params.fontSize))) {
		// Give font size units if it doesn't have any
		params.fontSize += 'px';
	}
	// Set font using given font properties
	ctx.font = params.fontStyle + ' ' + params.fontSize + ' ' + params.fontFamily;
}

// Measures canvas text
function _measureText(canvas, ctx, params, lines) {
	var originalSize, curWidth, l,
		propCache = caches.propCache;

	// Used cached width/height if possible
	if (propCache.text === params.text && propCache.fontStyle === params.fontStyle && propCache.fontSize === params.fontSize && propCache.fontFamily === params.fontFamily && propCache.maxWidth === params.maxWidth && propCache.lineHeight === params.lineHeight) {

		params.width = propCache.width;
		params.height = propCache.height;

	} else {
		// Calculate text dimensions only once

		// Calculate width of first line (for comparison)
		params.width = ctx.measureText(lines[0]).width;

		// Get width of longest line
		for (l = 1; l < lines.length; l += 1) {

			curWidth = ctx.measureText(lines[l]).width;
			// Ensure text's width is the width of its longest line
			if (curWidth > params.width) {
				params.width = curWidth;
			}

		}

		// Save original font size
		originalSize = canvas.style.fontSize;
		// Temporarily set canvas font size to retrieve size in pixels
		canvas.style.fontSize = params.fontSize;
		// Save text width and height in parameters object
		params.height = parseFloat($.css(canvas, 'fontSize')) * lines.length * params.lineHeight;
		// Reset font size to original size
		canvas.style.fontSize = originalSize;
	}
}

// Wraps a string of text within a defined width
function _wrapText(ctx, params) {
	var allText = String(params.text),
		// Maximum line width (optional)
		maxWidth = params.maxWidth,
		// Lines created by manual line breaks (\n)
		manualLines = allText.split('\n'),
		// All lines created manually and by wrapping
		allLines = [],
		// Other variables
		lines, line, l,
		text, words, w;

	// Loop through manually-broken lines
	for (l = 0; l < manualLines.length; l += 1) {

		text = manualLines[l];
		// Split line into list of words
		words = text.split(' ');
		lines = [];
		line = '';

		// If text is short enough initially
		// Or, if the text consists of only one word
		if (words.length === 1 || ctx.measureText(text).width < maxWidth) {

			// No need to wrap text
			lines = [text];

		} else {

			// Wrap lines
			for (w = 0; w < words.length; w += 1) {

				// Once line gets too wide, push word to next line
				if (ctx.measureText(line + words[w]).width > maxWidth) {
					// This check prevents empty lines from being created
					if (line !== '') {
						lines.push(line);
					}
					// Start new line and repeat process
					line = '';
				}
				// Add words to line until the line is too wide
				line += words[w];
				// Do not add a space after the last word
				if (w !== (words.length - 1)) {
					line += ' ';
				}
			}
			// The last word should always be pushed
			lines.push(line);

		}
		// Remove extra space at the end of each line
		allLines = allLines.concat(
			lines
			.join('\n')
			.replace(/((\n))|($)/gi, '$2')
			.split('\n')
		);

	}

	return allLines;
}

// Draws text on canvas
$.fn.drawText = function drawText(args) {
	var $canvases = this, e, ctx,
		params, layer,
		lines, line, l,
		fontSize, constantCloseness = 500,
		nchars, chars, ch, c,
		x, y;

	for (e = 0; e < $canvases.length; e += 1) {
		ctx = _getContext($canvases[e]);
		if (ctx) {

			params = new jCanvasObject(args);
			_addLayer($canvases[e], params, args, drawText);
			if (params.visible) {

				// Set text-specific properties
				ctx.textBaseline = params.baseline;
				ctx.textAlign = params.align;

				// Set canvas font using given properties
				_setCanvasFont($canvases[e], ctx, params);

				if (params.maxWidth !== null) {
					// Wrap text using an internal function
					lines = _wrapText(ctx, params);
				} else {
					// Convert string of text to list of lines
					lines = params.text
					.toString()
					.split('\n');
				}

				// Calculate text's width and height
				_measureText($canvases[e], ctx, params, lines);

				// If text is a layer
				if (layer) {
					// Copy calculated width/height to layer object
					layer.width = params.width;
					layer.height = params.height;
				}

				_transformShape($canvases[e], ctx, params, params.width, params.height);
				_setGlobalProps($canvases[e], ctx, params);

				// Adjust text position to accomodate different horizontal alignments
				x = params.x;
				if (params.align === 'left') {
					if (params.respectAlign) {
						// Realign text to the left if chosen
						params.x += params.width / 2;
					} else {
						// Center text block by default
						x -= params.width / 2;
					}
				} else if (params.align === 'right') {
					if (params.respectAlign) {
						// Realign text to the right if chosen
						params.x -= params.width / 2;
					} else {
						// Center text block by default
						x += params.width / 2;
					}
				}

				if (params.radius) {

					fontSize = parseFloat(params.fontSize);

					// Greater values move clockwise
					if (params.letterSpacing === null) {
						params.letterSpacing = fontSize / constantCloseness;
					}

					// Loop through each line of text
					for (l = 0; l < lines.length; l += 1) {
						ctx.save();
						ctx.translate(params.x, params.y);
						line = lines[l];
						if (params.flipArcText) {
							chars = line.split('');
							chars.reverse();
							line = chars.join('');
						}
						nchars = line.length;
						ctx.rotate(-(PI * params.letterSpacing * (nchars - 1)) / 2);
						// Loop through characters on each line
						for (c = 0; c < nchars; c += 1) {
							ch = line[c];
							// If character is not the first character
							if (c !== 0) {
								// Rotate character onto arc
								ctx.rotate(PI * params.letterSpacing);
							}
							ctx.save();
							ctx.translate(0, -params.radius);
							if (params.flipArcText) {
								ctx.scale(-1, -1);
							}
							ctx.fillText(ch, 0, 0);
							// Prevent extra shadow created by stroke (but only when fill is present)
							if (params.fillStyle !== 'transparent') {
								ctx.shadowColor = 'transparent';
							}
							if (params.strokeWidth !== 0) {
								// Only stroke if the stroke is not 0
								ctx.strokeText(ch, 0, 0);
							}
							ctx.restore();
						}
						params.radius -= fontSize;
						params.letterSpacing += fontSize / (constantCloseness * 2 * PI);
						ctx.restore();
					}

				} else {

					// Draw each line of text separately
					for (l = 0; l < lines.length; l += 1) {
						line = lines[l];
						// Add line offset to center point, but subtract some to center everything
						y = params.y + (l * params.height / lines.length) - (((lines.length - 1) * params.height / lines.length) / 2);

						ctx.shadowColor = params.shadowColor;

						// Fill & stroke text
						ctx.fillText(line, x, y);
						// Prevent extra shadow created by stroke (but only when fill is present)
						if (params.fillStyle !== 'transparent') {
							ctx.shadowColor = 'transparent';
						}
						if (params.strokeWidth !== 0) {
							// Only stroke if the stroke is not 0
							ctx.strokeText(line, x, y);
						}

					}

				}

				// Adjust bounding box according to text baseline
				y = 0;
				if (params.baseline === 'top') {
					y += params.height / 2;
				} else if (params.baseline === 'bottom') {
					y -= params.height / 2;
				}

				// Detect jCanvas events
				if (params._event) {
					ctx.beginPath();
					ctx.rect(
						params.x - (params.width / 2),
						params.y - (params.height / 2) + y,
						params.width,
						params.height
					);
					_detectEvents($canvases[e], ctx, params);
					// Close path and configure masking
					ctx.closePath();
				}
				_restoreTransform(ctx, params);

			}
		}
	}
	// Cache jCanvas parameters object for efficiency
	caches.propCache = params;
	return $canvases;
};

// Measures text width/height using the given parameters
$.fn.measureText = function measureText(args) {
	var $canvases = this, ctx,
		params, lines;

	// Attempt to retrieve layer
	params = $canvases.getLayer(args);
	// If layer does not exist or if returned object is not a jCanvas layer
	if (!params || (params && !params._layer)) {
		params = new jCanvasObject(args);
	}

	ctx = _getContext($canvases[0]);
	if (ctx) {

		// Set canvas font using given properties
		_setCanvasFont($canvases[0], ctx, params);
		// Calculate width and height of text
		if (params.maxWidth !== null) {
			lines = _wrapText(ctx, params);
		} else {
			lines = params.text.split('\n');
		}
		_measureText($canvases[0], ctx, params, lines);


	}

	return params;
};

/* Image API */

// Draws image on canvas
$.fn.drawImage = function drawImage(args) {
	var $canvases = this, canvas, e, ctx, data,
		params, layer,
		img, imgCtx, source,
		imageCache = caches.imageCache;

	// Draw image function
	function draw(canvas, ctx, data, params, layer) {

		// If width and sWidth are not defined, use image width
		if (params.width === null && params.sWidth === null) {
			params.width = params.sWidth = img.width;
		}
		// If width and sHeight are not defined, use image height
		if (params.height === null && params.sHeight === null) {
			params.height = params.sHeight = img.height;
		}

		// Ensure image layer's width and height are accurate
		if (layer) {
			layer.width = params.width;
			layer.height = params.height;
		}

		// Only crop image if all cropping properties are given
		if (params.sWidth !== null && params.sHeight !== null && params.sx !== null && params.sy !== null) {

			// If width is not defined, use the given sWidth
			if (params.width === null) {
				params.width = params.sWidth;
			}
			// If height is not defined, use the given sHeight
			if (params.height === null) {
				params.height = params.sHeight;
			}

			// Optionally crop from top-left corner of region
			if (params.cropFromCenter) {
				params.sx += params.sWidth / 2;
				params.sy += params.sHeight / 2;
			}

			// Ensure cropped region does not escape image boundaries

			// Top
			if ((params.sy - (params.sHeight / 2)) < 0) {
				params.sy = (params.sHeight / 2);
			}
			// Bottom
			if ((params.sy + (params.sHeight / 2)) > img.height) {
				params.sy = img.height - (params.sHeight / 2);
			}
			// Left
			if ((params.sx - (params.sWidth / 2)) < 0) {
				params.sx = (params.sWidth / 2);
			}
			// Right
			if ((params.sx + (params.sWidth / 2)) > img.width) {
				params.sx = img.width - (params.sWidth / 2);
			}

			_transformShape(canvas, ctx, params, params.width, params.height);
			_setGlobalProps(canvas, ctx, params);

			// Draw image
			ctx.drawImage(
				img,
				params.sx - (params.sWidth / 2),
				params.sy - (params.sHeight / 2),
				params.sWidth,
				params.sHeight,
				params.x - (params.width / 2),
				params.y - (params.height / 2),
				params.width,
				params.height
			);

		} else {
			// Show entire image if no crop region is defined

			_transformShape(canvas, ctx, params, params.width, params.height);
			_setGlobalProps(canvas, ctx, params);

			// Draw image on canvas
			ctx.drawImage(
				img,
				params.x - (params.width / 2),
				params.y - (params.height / 2),
				params.width,
				params.height
			);

		}

		// Draw invisible rectangle to allow for events and masking
		ctx.beginPath();
		ctx.rect(
			params.x - (params.width / 2),
			params.y - (params.height / 2),
			params.width,
			params.height
		);
		// Check for jCanvas events
		_detectEvents(canvas, ctx, params);
		// Close path and configure masking
		ctx.closePath();
		_restoreTransform(ctx, params);
		_enableMasking(ctx, data, params);
	}
	// On load function
	function onload(canvas, ctx, data, params, layer) {
		return function () {
			var $canvas = $(canvas);
			draw(canvas, ctx, data, params, layer);
			if (params.layer) {
				// Trigger 'load' event for layers
				_triggerLayerEvent($canvas, data, layer, 'load');
			} else if (params.load) {
				// Run 'load' callback for non-layers
				params.load.call($canvas[0], layer);
			}
			// Continue drawing successive layers after this image layer has loaded
			if (params.layer) {
				// Store list of previous masks for each layer
				layer._masks = data.transforms.masks.slice(0);
				if (params._next) {
					// Draw successive layers
					$canvas.drawLayers({
						clear: false,
						resetFire: true,
						index: params._next
					});
				}
			}
		};
	}
	for (e = 0; e < $canvases.length; e += 1) {
		canvas = $canvases[e];
		ctx = _getContext($canvases[e]);
		if (ctx) {

			data = _getCanvasData($canvases[e]);
			params = new jCanvasObject(args);
			layer = _addLayer($canvases[e], params, args, drawImage);
			if (params.visible) {

				// Cache the given source
				source = params.source;

				imgCtx = source.getContext;
				if (source.src || imgCtx) {
					// Use image or canvas element if given
					img = source;
				} else if (source) {
					if (imageCache[source] && imageCache[source].complete) {
						// Get the image element from the cache if possible
						img = imageCache[source];
					} else {
						// Otherwise, get the image from the given source URL
						img = new Image();
						// If source URL is not a data URL
						if (!source.match(/^data:/i)) {
							// Set crossOrigin for this image
							img.crossOrigin = params.crossOrigin;
						}
						img.src = source;
						// Save image in cache for improved performance
						imageCache[source] = img;
					}
				}

				if (img) {
					if (img.complete || imgCtx) {
						// Draw image if already loaded
						onload(canvas, ctx, data, params, layer)();
					} else {
						// Otherwise, draw image when it loads
						img.onload = onload(canvas, ctx, data, params, layer);
						// Fix onload() bug in IE9
						img.src = img.src;
					}
				}

			}
		}
	}
	return $canvases;
};

// Creates a canvas pattern object
$.fn.createPattern = function createPattern(args) {
	var $canvases = this, ctx,
		params,
		img, imgCtx,
		pattern, source;

	// Function to be called when pattern loads
	function onload() {
		// Create pattern
		pattern = ctx.createPattern(img, params.repeat);
		// Run callback function if defined
		if (params.load) {
			params.load.call($canvases[0], pattern);
		}
	}

	ctx = _getContext($canvases[0]);
	if (ctx) {

		params = new jCanvasObject(args);

		// Cache the given source
		source = params.source;

		// Draw when image is loaded (if load() callback function is defined)

		if (isFunction(source)) {
			// Draw pattern using function if given

			img = $('<canvas />')[0];
			img.width = params.width;
			img.height = params.height;
			imgCtx = _getContext(img);
			source.call(img, imgCtx);
			onload();

		} else {
			// Otherwise, draw pattern using source image

			imgCtx = source.getContext;
			if (source.src || imgCtx) {
				// Use image element if given
				img = source;
			} else {
				// Use URL if given to get the image
				img = new Image();
				// If source URL is not a data URL
				if (!source.match(/^data:/i)) {
					// Set crossOrigin for this image
					img.crossOrigin = params.crossOrigin;
				}
				img.src = source;
			}

			// Create pattern if already loaded
			if (img.complete || imgCtx) {
				onload();
			} else {
				img.onload = onload;
				// Fix onload() bug in IE9
				img.src = img.src;
			}

		}

	} else {

		pattern = null;

	}
	return pattern;
};

// Creates a canvas gradient object
$.fn.createGradient = function createGradient(args) {
	var $canvases = this, ctx,
		params,
		gradient,
		stops = [], nstops,
		start, end,
		i, a, n, p;

	params = new jCanvasObject(args);
	ctx = _getContext($canvases[0]);
	if (ctx) {

		// Gradient coordinates must be defined
		params.x1 = params.x1 || 0;
		params.y1 = params.y1 || 0;
		params.x2 = params.x2 || 0;
		params.y2 = params.y2 || 0;

		if (params.r1 !== null && params.r2 !== null) {
			// Create radial gradient if chosen
			gradient = ctx.createRadialGradient(params.x1, params.y1, params.r1, params.x2, params.y2, params.r2);
		} else {
			// Otherwise, create a linear gradient by default
			gradient = ctx.createLinearGradient(params.x1, params.y1, params.x2, params.y2);
		}

		// Count number of color stops
		for (i = 1; params['c' + i] !== undefined; i += 1) {
			if (params['s' + i] !== undefined) {
				stops.push(params['s' + i]);
			} else {
				stops.push(null);
			}
		}
		nstops = stops.length;

		// Define start stop if not already defined
		if (stops[0] === null) {
			stops[0] = 0;
		}
		// Define end stop if not already defined
		if (stops[nstops - 1] === null) {
			stops[nstops - 1] = 1;
		}

		// Loop through color stops to fill in the blanks
		for (i = 0; i < nstops; i += 1) {
			// A progression, in this context, is defined as all of the color stops between and including two known color stops

			if (stops[i] !== null) {
				// Start a new progression if stop is a number

				// Number of stops in current progression
				n = 1;
				// Current iteration in current progression
				p = 0;
				start = stops[i];

				// Look ahead to find end stop
				for (a = (i + 1); a < nstops; a += 1) {
					if (stops[a] !== null) {
						// If this future stop is a number, make it the end stop for this progression
						end = stops[a];
						break;
					} else {
						// Otherwise, keep looking ahead
						n += 1;
					}
				}

				// Ensure start stop is not greater than end stop
				if (start > end) {
					stops[a] = stops[i];
				}

			} else if (stops[i] === null) {
				// Calculate stop if not initially given
				p += 1;
				stops[i] = start + (p * ((end - start) / n));
			}
			// Add color stop to gradient object
			gradient.addColorStop(stops[i], params['c' + (i + 1)]);
		}

	} else {
		gradient = null;
	}
	return gradient;
};

// Manipulates pixels on the canvas
$.fn.setPixels = function setPixels(args) {
	var $canvases = this,
		canvas, e, ctx, canvasData,
		params,
		px,
		imgData, pixelData, i, len;

	for (e = 0; e < $canvases.length; e += 1) {
		canvas = $canvases[e];
		ctx = _getContext(canvas);
		canvasData = _getCanvasData($canvases[e]);
		if (ctx) {

			params = new jCanvasObject(args);
			_addLayer(canvas, params, args, setPixels);
			_transformShape($canvases[e], ctx, params, params.width, params.height);

			// Use entire canvas of x, y, width, or height is not defined
			if (params.width === null || params.height === null) {
				params.width = canvas.width;
				params.height = canvas.height;
				params.x = params.width / 2;
				params.y = params.height / 2;
			}

			if (params.width !== 0 && params.height !== 0) {
				// Only set pixels if width and height are not zero

				imgData = ctx.getImageData(
					(params.x - (params.width / 2)) * canvasData.pixelRatio,
					(params.y - (params.height / 2)) * canvasData.pixelRatio,
					params.width * canvasData.pixelRatio,
					params.height * canvasData.pixelRatio
				);
				pixelData = imgData.data;
				len = pixelData.length;

				// Loop through pixels with the "each" callback function
				if (params.each) {
					for (i = 0; i < len; i += 4) {
						px = {
							r: pixelData[i],
							g: pixelData[i + 1],
							b: pixelData[i + 2],
							a: pixelData[i + 3]
						};
						params.each.call(canvas, px, params);
						pixelData[i] = px.r;
						pixelData[i + 1] = px.g;
						pixelData[i + 2] = px.b;
						pixelData[i + 3] = px.a;
					}
				}
				// Put pixels on canvas
				ctx.putImageData(
					imgData,
					(params.x - (params.width / 2)) * canvasData.pixelRatio,
					(params.y - (params.height / 2)) * canvasData.pixelRatio
				);
				// Restore transformation
				ctx.restore();

			}

		}
	}
	return $canvases;
};

// Retrieves canvas image as data URL
$.fn.getCanvasImage = function getCanvasImage(type, quality) {
	var $canvases = this, canvas,
		dataURL = null;
	if ($canvases.length !== 0) {
		canvas = $canvases[0];
		if (canvas.toDataURL) {
			// JPEG quality defaults to 1
			if (quality === undefined) {
				quality = 1;
			}
			dataURL = canvas.toDataURL('image/' + type, quality);
		}
	}
	return dataURL;
};

// Scales canvas based on the device's pixel ratio
$.fn.detectPixelRatio = function detectPixelRatio(callback) {
	var $canvases = this,
		canvas, e, ctx,
		devicePixelRatio, backingStoreRatio, ratio,
		oldWidth, oldHeight,
		data;

	for (e = 0; e < $canvases.length; e += 1) {
		// Get canvas and its associated data
		canvas = $canvases[e];
		ctx = _getContext(canvas);
		data = _getCanvasData($canvases[e]);

		// If canvas has not already been scaled with this method
		if (!data.scaled) {

			// Determine device pixel ratios
			devicePixelRatio = window.devicePixelRatio || 1;
			backingStoreRatio = ctx.webkitBackingStorePixelRatio ||
				ctx.mozBackingStorePixelRatio ||
				ctx.msBackingStorePixelRatio ||
				ctx.oBackingStorePixelRatio ||
				ctx.backingStorePixelRatio || 1;

			// Calculate general ratio based on the two given ratios
			ratio = devicePixelRatio / backingStoreRatio;

			if (ratio !== 1) {
				// Scale canvas relative to ratio

				// Get the current canvas dimensions for future use
				oldWidth = canvas.width;
				oldHeight = canvas.height;

				// Resize canvas relative to the determined ratio
				canvas.width = oldWidth * ratio;
				canvas.height = oldHeight * ratio;

				// Scale canvas back to original dimensions via CSS
				canvas.style.width = oldWidth + 'px';
				canvas.style.height = oldHeight + 'px';

				// Scale context to counter the manual scaling of canvas
				ctx.scale(ratio, ratio);

			}

			// Set pixel ratio on canvas data object
			data.pixelRatio = ratio;
			// Ensure that this method can only be called once for any given canvas
			data.scaled = true;

			// Call the given callback function with the ratio as its only argument
			if (callback) {
				callback.call(canvas, ratio);
			}

		}

	}
	return $canvases;
};

// Clears the jCanvas cache
jCanvas.clearCache = function clearCache() {
	var cacheName;
	for (cacheName in caches) {
		if (Object.prototype.hasOwnProperty.call(caches, cacheName)) {
			caches[cacheName] = {};
		}
	}
};

// Enable canvas feature detection with $.support
$.support.canvas = ($('<canvas />')[0].getContext !== undefined);

// Export jCanvas functions
extendObject(jCanvas, {
	defaults: defaults,
	setGlobalProps: _setGlobalProps,
	transformShape: _transformShape,
	detectEvents: _detectEvents,
	closePath: _closePath,
	setCanvasFont: _setCanvasFont,
	measureText: _measureText
});
$.jCanvas = jCanvas;
$.jCanvasObject = jCanvasObject;

}));