vueCropper.vue 56.6 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
<template>
  <div
    class="vue-cropper"
    ref="cropper"
    @mouseover="scaleImg"
    @mouseout="cancelScale"
  >
    <!-- :style="{width:w+'px',height:h+'px'}" -->
    <div class="cropper-box">
      <div
        class="cropper-box-canvas"
        v-show="!loading"
        :style="{
          width: trueWidth + 'px',
          height: trueHeight + 'px',
          transform:
            'scale(' +
            scale +
            ',' +
            scale +
            ') ' +
            'translate3d(' +
            x / scale +
            'px,' +
            y / scale +
            'px,' +
            '0)' +
            'rotateZ(' +
            rotate * 90 +
            'deg)'
        }"
      >
        <img :src="imgs" alt="cropper-img" ref="cropperImg" />
      </div>
    </div>
    <div
      class="cropper-drag-box"
      :class="{
        'cropper-move': move && !crop,
        'cropper-crop': crop,
        'cropper-modal': cropping
      }"
      @mousedown="startMove"
      @touchstart="startMove"
    ></div>
    <div
      v-show="cropping"
      class="cropper-crop-box"
      :style="{
        width: cropW + 'px',
        height: cropH + 'px',
        transform:
          'translate3d(' + cropOffsertX + 'px,' + cropOffsertY + 'px,' + '0)'
      }"
    >
      <span class="cropper-view-box">
        <img
          :style="{
            width: trueWidth + 'px',
            height: trueHeight + 'px',
            transform:
              'scale(' +
              scale +
              ',' +
              scale +
              ') ' +
              'translate3d(' +
              (x - cropOffsertX) / scale +
              'px,' +
              (y - cropOffsertY) / scale +
              'px,' +
              '0)' +
              'rotateZ(' +
              rotate * 90 +
              'deg)'
          }"
          :src="imgs"
          alt="cropper-img"
        />
      </span>
      <span
        class="cropper-face cropper-move"
        @mousedown="cropMove"
        @touchstart="cropMove"
      ></span>
      <span class="crop-info" v-if="info" :style="{ top: cropInfo.top }"
        >{{ this.cropInfo.width }} × {{ this.cropInfo.height }}</span
      >
      <span v-if="!fixedBox">
        <span
          class="crop-line line-w"
          @mousedown="changeCropSize($event, false, true, 0, 1)"
          @touchstart="changeCropSize($event, false, true, 0, 1)"
        ></span>
        <span
          class="crop-line line-a"
          @mousedown="changeCropSize($event, true, false, 1, 0)"
          @touchstart="changeCropSize($event, true, false, 1, 0)"
        ></span>
        <span
          class="crop-line line-s"
          @mousedown="changeCropSize($event, false, true, 0, 2)"
          @touchstart="changeCropSize($event, false, true, 0, 2)"
        ></span>
        <span
          class="crop-line line-d"
          @mousedown="changeCropSize($event, true, false, 2, 0)"
          @touchstart="changeCropSize($event, true, false, 2, 0)"
        ></span>
        <span
          class="crop-point point1"
          @mousedown="changeCropSize($event, true, true, 1, 1)"
          @touchstart="changeCropSize($event, true, true, 1, 1)"
        ></span>
        <span
          class="crop-point point2"
          @mousedown="changeCropSize($event, false, true, 0, 1)"
          @touchstart="changeCropSize($event, false, true, 0, 1)"
        ></span>
        <span
          class="crop-point point3"
          @mousedown="changeCropSize($event, true, true, 2, 1)"
          @touchstart="changeCropSize($event, true, true, 2, 1)"
        ></span>
        <span
          class="crop-point point4"
          @mousedown="changeCropSize($event, true, false, 1, 0)"
          @touchstart="changeCropSize($event, true, false, 1, 0)"
        ></span>
        <span
          class="crop-point point5"
          @mousedown="changeCropSize($event, true, false, 2, 0)"
          @touchstart="changeCropSize($event, true, false, 2, 0)"
        ></span>
        <span
          class="crop-point point6"
          @mousedown="changeCropSize($event, true, true, 1, 2)"
          @touchstart="changeCropSize($event, true, true, 1, 2)"
        ></span>
        <span
          class="crop-point point7"
          @mousedown="changeCropSize($event, false, true, 0, 2)"
          @touchstart="changeCropSize($event, false, true, 0, 2)"
        ></span>
        <span
          class="crop-point point8"
          @mousedown="changeCropSize($event, true, true, 2, 2)"
          @touchstart="changeCropSize($event, true, true, 2, 2)"
        ></span>
      </span>
    </div>
  </div>
</template>

<script>
import exifmin from './exif-js-min'

export default {
  data: function() {
    return {
      // 容器高宽
      w: 0,
      h: 0,
      // 图片缩放比例
      scale: 1,
      // 图片偏移x轴
      x: 0,
      // 图片偏移y轴
      y: 0,
      // 图片加载
      loading: true,
      // 图片真实宽度
      trueWidth: 0,
      // 图片真实高度
      trueHeight: 0,
      move: true,
      // 移动的x
      moveX: 0,
      // 移动的y
      moveY: 0,
      // 开启截图
      crop: false,
      // 正在截图
      cropping: false,
      // 裁剪框大小
      cropW: 0,
      cropH: 0,
      cropOldW: 0,
      cropOldH: 0,
      // 判断是否能够改变
      canChangeX: false,
      canChangeY: false,
      // 改变的基准点
      changeCropTypeX: 1,
      changeCropTypeY: 1,
      // 裁剪框的坐标轴
      cropX: 0,
      cropY: 0,
      cropChangeX: 0,
      cropChangeY: 0,
      cropOffsertX: 0,
      cropOffsertY: 0,
      // 支持的滚动事件
      support: '',
      // 移动端手指缩放
      touches: [],
      touchNow: false,
      // 图片旋转
      rotate: 0,
      isIos: false,
      orientation: 0,
      imgs: '',
      // 图片缩放系数
      coe: 0.2,
      // 是否正在多次缩放
      scaling: false,
      scalingSet: '',
      coeStatus: '',
      // 控制emit触发频率
      isCanShow: true
    }
  },
  props: {
    img: {
      type: [String, Blob, null, File],
      default: ''
    },
    // 输出图片压缩比
    outputSize: {
      type: Number,
      default: 1
    },
    outputType: {
      type: String,
      default: 'jpeg'
    },
    info: {
      type: Boolean,
      default: true
    },
    // 是否开启滚轮放大缩小
    canScale: {
      type: Boolean,
      default: true
    },
    // 是否自成截图框
    autoCrop: {
      type: Boolean,
      default: false
    },
    autoCropWidth: {
      type: [Number, String],
      default: 0
    },
    autoCropHeight: {
      type: [Number, String],
      default: 0
    },
    // 是否开启固定宽高比
    fixed: {
      type: Boolean,
      default: false
    },
    // 宽高比 w/h
    fixedNumber: {
      type: Array,
      default: () => {
        return [1, 1]
      }
    },
    // 固定大小 禁止改变截图框大小
    fixedBox: {
      type: Boolean,
      default: false
    },
    // 输出截图是否缩放
    full: {
      type: Boolean,
      default: false
    },
    // 是否可以拖动图片
    canMove: {
      type: Boolean,
      default: true
    },
    // 是否可以拖动截图框
    canMoveBox: {
      type: Boolean,
      default: true
    },
    // 上传图片按照原始比例显示
    original: {
      type: Boolean,
      default: false
    },
    // 截图框能否超过图片
    centerBox: {
      type: Boolean,
      default: false
    },
    // 是否根据dpr输出高清图片
    high: {
      type: Boolean,
      default: true
    },
    // 截图框展示宽高类型
    infoTrue: {
      type: Boolean,
      default: false
    },
    // 可以压缩图片宽高  默认不超过10000
    maxImgSize: {
      type: Number,
      default: 10000
    },
    // 倍数  可渲染当前截图框的n倍 0 - 1000;
    enlarge: {
      type: [Number, String],
      default: 1
    },

    // 自动预览的固定宽度
    preW: {
      type: [Number, String],
      default: 0
    },
    /*
      图片布局方式 mode 实现和css背景一样的效果
      contain  居中布局 默认不会缩放 保证图片在容器里面 mode: 'contain'
      cover    拉伸布局 填充整个容器  mode: 'cover'
      如果仅有一个数值被给定,这个数值将作为宽度值大小,高度值将被设定为auto。 mode: '50px'
      如果有两个数值被给定,第一个将作为宽度值大小,第二个作为高度值大小。 mode: '50px 60px'
    */
    mode: {
      type: String,
      default: 'contain'
    }
  },
  computed: {
    cropInfo() {
      let obj = {}
      obj.top = this.cropOffsertY > 21 ? '-21px' : '0px'
      obj.width = this.cropW > 0 ? this.cropW : 0
      obj.height = this.cropH > 0 ? this.cropH : 0
      if (this.infoTrue) {
        let dpr = 1
        if (this.high && !this.full) {
          dpr = window.devicePixelRatio
        }
        if ((this.enlarge !== 1) & !this.full) {
          dpr = Math.abs(Number(this.enlarge))
        }
        obj.width = obj.width * dpr
        obj.height = obj.height * dpr
        if (this.full) {
          obj.width = obj.width / this.scale
          obj.height = obj.height / this.scale
        }
      }
      obj.width = obj.width.toFixed(0)
      obj.height = obj.height.toFixed(0)
      return obj
    },

    isIE() {
      var userAgent = navigator.userAgent // 取得浏览器的userAgent字符串
      var isIE =
        userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1 // 判断是否IE浏览器
      return isIE
    }
  },
  watch: {
    // 如果图片改变, 重新布局
    img() {
      // 当传入图片时, 读取图片信息同时展示
      this.checkedImg()
    },
    imgs(val) {
      if (val === '') {
        return
      }
      this.reload()
    },
    cropW() {
      this.showPreview()
    },
    cropH() {
      this.showPreview()
    },
    cropOffsertX() {
      this.showPreview()
    },
    cropOffsertY() {
      this.showPreview()
    },
    scale(val, oldVal) {
      this.showPreview()
    },
    x() {
      this.showPreview()
    },
    y() {
      this.showPreview()
    },
    autoCrop(val) {
      if (val) {
        this.goAutoCrop()
      }
    },
    // 修改了自动截图框
    autoCropWidth() {
      if (this.autoCrop) {
        this.goAutoCrop()
      }
    },
    autoCropHeight() {
      if (this.autoCrop) {
        this.goAutoCrop()
      }
    },
    mode() {
      this.checkedImg()
    },
    rotate() {
      this.showPreview()
      if (this.autoCrop) {
        this.goAutoCrop(this.cropW, this.cropH)
      } else {
        if (this.cropW > 0 || this.cropH > 0) {
          this.goAutoCrop(this.cropW, this.cropH)
        }
      }
    }
  },
  methods: {
    checkOrientationImage(img, orientation, width, height) {
      let canvas = document.createElement('canvas')
      let ctx = canvas.getContext('2d')
      ctx.save()

      switch (orientation) {
        case 2:
          canvas.width = width
          canvas.height = height
          // horizontal flip
          ctx.translate(width, 0)
          ctx.scale(-1, 1)
          break
        case 3:
          canvas.width = width
          canvas.height = height
          // 180 graus
          ctx.translate(width / 2, height / 2)
          ctx.rotate((180 * Math.PI) / 180)
          ctx.translate(-width / 2, -height / 2)
          break
        case 4:
          canvas.width = width
          canvas.height = height
          // vertical flip
          ctx.translate(0, height)
          ctx.scale(1, -1)
          break
        case 5:
          // vertical flip + 90 rotate right
          canvas.height = width
          canvas.width = height
          ctx.rotate(0.5 * Math.PI)
          ctx.scale(1, -1)
          break
        case 6:
          canvas.width = height
          canvas.height = width
          // 90 graus
          ctx.translate(height / 2, width / 2)
          ctx.rotate((90 * Math.PI) / 180)
          ctx.translate(-width / 2, -height / 2)
          break
        case 7:
          // horizontal flip + 90 rotate right
          canvas.height = width
          canvas.width = height
          ctx.rotate(0.5 * Math.PI)
          ctx.translate(width, -height)
          ctx.scale(-1, 1)
          break
        case 8:
          canvas.height = width
          canvas.width = height
          // -90 graus
          ctx.translate(height / 2, width / 2)
          ctx.rotate((-90 * Math.PI) / 180)
          ctx.translate(-width / 2, -height / 2)
          break
        default:
          canvas.width = width
          canvas.height = height
      }

      ctx.drawImage(img, 0, 0, width, height)
      ctx.restore()
      canvas.toBlob(
        blob => {
          let data = URL.createObjectURL(blob)
          this.imgs = data
        },
        'image/' + this.outputType,
        1
      )
    },

    // checkout img
    checkedImg() {
      if (this.img === '') return
      this.loading = true
      this.scale = 1
      this.rotate = 0
      this.clearCrop()
      let img = new Image()
      img.onload = () => {
        if (this.img === '') {
          this.$emit('imgLoad', 'error')
          return false
        }

        let width = img.width
        let height = img.height
        exifmin.getData(img).then(data => {
          this.orientation = data.orientation || 1
          let max = this.maxImgSize
          if (!this.orientation && (width < max) & (height < max)) {
            this.imgs = this.img
            return
          }

          if (width > max) {
            height = (height / width) * max
            width = max
          }

          if (height > max) {
            width = (width / height) * max
            height = max
          }

          this.checkOrientationImage(img, this.orientation, width, height)
        })
      }

      img.onerror = () => {
        this.$emit('imgLoad', 'error')
      }

      // 判断如果不是base64图片 再添加crossOrigin属性,否则会导致iOS低版本(10.2)无法显示图片
      if (this.img.substr(0, 4) !== 'data') {
        img.crossOrigin = ''
      }

      if (this.isIE) {
        var xhr = new XMLHttpRequest()
        xhr.onload = function() {
          var url = URL.createObjectURL(this.response)
          img.src = url
        }
        xhr.open('GET', this.img, true)
        xhr.responseType = 'blob'
        xhr.send()
      } else {
        img.src = this.img
      }
    },
    // 当按下鼠标键
    startMove(e) {
      e.preventDefault()
      // 如果move 为true 表示当前可以拖动
      if (this.move && !this.crop) {
        if (!this.canMove) {
          return false
        }
        // 开始移动
        this.moveX = (e.clientX ? e.clientX : e.touches[0].clientX) - this.x
        this.moveY = (e.clientY ? e.clientY : e.touches[0].clientY) - this.y
        if (e.touches) {
          window.addEventListener('touchmove', this.moveImg)
          window.addEventListener('touchend', this.leaveImg)
          if (e.touches.length == 2) {
            // 记录手指刚刚放上去
            this.touches = e.touches
            window.addEventListener('touchmove', this.touchScale)
            window.addEventListener('touchend', this.cancelTouchScale)
          }
        } else {
          window.addEventListener('mousemove', this.moveImg)
          window.addEventListener('mouseup', this.leaveImg)
        }
        // 触发图片移动事件
        this.$emit('imgMoving', {
          moving: true,
          axis: this.getImgAxis()
        })
      } else {
        // 截图ing
        this.cropping = true
        // 绑定截图事件
        window.addEventListener('mousemove', this.createCrop)
        window.addEventListener('mouseup', this.endCrop)
        window.addEventListener('touchmove', this.createCrop)
        window.addEventListener('touchend', this.endCrop)
        this.cropOffsertX = e.offsetX
          ? e.offsetX
          : e.touches[0].pageX - this.$refs.cropper.offsetLeft
        this.cropOffsertY = e.offsetY
          ? e.offsetY
          : e.touches[0].pageY - this.$refs.cropper.offsetTop
        this.cropX = e.clientX ? e.clientX : e.touches[0].clientX
        this.cropY = e.clientY ? e.clientY : e.touches[0].clientY
        this.cropChangeX = this.cropOffsertX
        this.cropChangeY = this.cropOffsertY
        this.cropW = 0
        this.cropH = 0
        console.log(
          'cropOffsertX',
          this.cropOffsertX,
          'cropOffsertY',
          this.cropOffsertY,
          'cropX',
          this.cropX,
          'cropY',
          this.cropY
        )
      }
    },

    // 移动端缩放
    // touchScale(e) {
    //   e.preventDefault()
    //   let scale = this.scale
    //   // 记录变化量
    //   // 第一根手指
    //   var oldTouch1 = {
    //     x: this.touches[0].clientX,
    //     y: this.touches[0].clientY
    //   }
    //   var newTouch1 = {
    //     x: e.touches[0].clientX,
    //     y: e.touches[0].clientY
    //   }
    //   // 第二根手指
    //   var oldTouch2 = {
    //     x: this.touches[1].clientX,
    //     y: this.touches[1].clientY
    //   }
    //   var newTouch2 = {
    //     x: e.touches[1].clientX,
    //     y: e.touches[1].clientY
    //   }
    //   var oldL = Math.sqrt(
    //     Math.pow(oldTouch1.x - oldTouch2.x, 2) +
    //       Math.pow(oldTouch1.y - oldTouch2.y, 2)
    //   )
    //   var newL = Math.sqrt(
    //     Math.pow(newTouch1.x - newTouch2.x, 2) +
    //       Math.pow(newTouch1.y - newTouch2.y, 2)
    //   )
    //   var cha = newL - oldL
    //   // 根据图片本身大小 决定每次改变大小的系数, 图片越大系数越小
    //   // 1px - 0.2
    //   var coe = 1
    //   coe =
    //     coe / this.trueWidth > coe / this.trueHeight
    //       ? coe / this.trueHeight
    //       : coe / this.trueWidth
    //   coe = coe > 0.1 ? 0.1 : coe
    //   var num = coe * cha
    //   if (!this.touchNow) {
    //     this.touchNow = true
    //     if (cha > 0) {
    //       scale += Math.abs(num)
    //     } else if (cha < 0) {
    //       scale > Math.abs(num) ? (scale -= Math.abs(num)) : scale
    //     }
    //     this.touches = e.touches
    //     setTimeout(() => {
    //       this.touchNow = false
    //     }, 8)
    //     if (!this.checkoutImgAxis(this.x, this.y, scale)) {
    //       return false
    //     }
    //     this.scale = scale
    //   }
    // },

    // cancelTouchScale(e) {
    //   window.removeEventListener('touchmove', this.touchScale)
    // },

    // 移动图片
    moveImg(e) {
      e.preventDefault()
      if (e.touches && e.touches.length === 2) {
        this.touches = e.touches
        window.addEventListener('touchmove', this.touchScale)
        window.addEventListener('touchend', this.cancelTouchScale)
        window.removeEventListener('touchmove', this.moveImg)
        return false
      }
      let nowX = e.clientX ? e.clientX : e.touches[0].clientX
      let nowY = e.clientY ? e.clientY : e.touches[0].clientY

      let changeX, changeY
      changeX = nowX - this.moveX
      changeY = nowY - this.moveY

      this.$nextTick(() => {
        if (this.centerBox) {
          let axis = this.getImgAxis(changeX, changeY, this.scale)
          let cropAxis = this.getCropAxis()
          let imgW = this.trueHeight * this.scale
          let imgH = this.trueWidth * this.scale
          let maxLeft, maxTop, maxRight, maxBottom
          switch (this.rotate) {
            case 1:
            case -1:
            case 3:
            case -3:
              maxLeft =
                this.cropOffsertX -
                (this.trueWidth * (1 - this.scale)) / 2 +
                (imgW - imgH) / 2
              maxTop =
                this.cropOffsertY -
                (this.trueHeight * (1 - this.scale)) / 2 +
                (imgH - imgW) / 2
              maxRight = maxLeft - imgW + this.cropW
              maxBottom = maxTop - imgH + this.cropH
              break
            default:
              maxLeft =
                this.cropOffsertX - (this.trueWidth * (1 - this.scale)) / 2
              maxTop =
                this.cropOffsertY - (this.trueHeight * (1 - this.scale)) / 2
              maxRight = maxLeft - imgH + this.cropW
              maxBottom = maxTop - imgW + this.cropH
              break
          }

          // 图片左边 图片不能超过截图框
          if (axis.x1 >= cropAxis.x1) {
            changeX = maxLeft
          }

          // 图片上边 图片不能超过截图框
          if (axis.y1 >= cropAxis.y1) {
            changeY = maxTop
          }

          // 图片右边
          if (axis.x2 <= cropAxis.x2) {
            changeX = maxRight
          }

          // 图片下边
          if (axis.y2 <= cropAxis.y2) {
            changeY = maxBottom
          }
        }
        this.x = changeX
        this.y = changeY
        // 触发图片移动事件
        this.$emit('imgMoving', {
          moving: true,
          axis: this.getImgAxis()
        })
      })
    },
    // 移动图片结束
    leaveImg(e) {
      window.removeEventListener('mousemove', this.moveImg)
      window.removeEventListener('touchmove', this.moveImg)
      window.removeEventListener('mouseup', this.leaveImg)
      window.removeEventListener('touchend', this.leaveImg)
      // 触发图片移动事件
      this.$emit('imgMoving', {
        moving: false,
        axis: this.getImgAxis()
      })
    },
    // 缩放图片
    scaleImg() {
      if (this.canScale) {
        window.addEventListener(this.support, this.changeSize, {
          passive: false
        })
      }
    },
    // 移出框
    cancelScale() {
      if (this.canScale) {
        window.removeEventListener(this.support, this.changeSize)
      }
    },
    // 改变大小函数
    changeSize(e) {
      e.preventDefault()
      let scale = this.scale
      var change = e.deltaY || e.wheelDelta
      // 根据图片本身大小 决定每次改变大小的系数, 图片越大系数越小
      var isFirefox = navigator.userAgent.indexOf('Firefox')
      change = isFirefox > 0 ? change * 30 : change
      // 修复ie的滚动缩放
      if (this.isIE) {
        change = -change
      }
      // 1px - 0.2
      var coe = this.coe
      coe =
        coe / this.trueWidth > coe / this.trueHeight
          ? coe / this.trueHeight
          : coe / this.trueWidth
      var num = coe * change
      num < 0
        ? (scale += Math.abs(num))
        : scale > Math.abs(num)
        ? (scale -= Math.abs(num))
        : scale
      // 延迟0.1s 每次放大大或者缩小的范围
      let status = num < 0 ? 'add' : 'reduce'
      if (status !== this.coeStatus) {
        this.coeStatus = status
        this.coe = 0.2
      }
      if (!this.scaling) {
        this.scalingSet = setTimeout(() => {
          this.scaling = false
          this.coe = this.coe += 0.01
        }, 50)
      }
      this.scaling = true
      if (!this.checkoutImgAxis(this.x, this.y, scale)) {
        return false
      }
      this.scale = scale
    },

    // 修改图片大小函数
    changeScale(num) {
      let scale = this.scale
      num = num || 1
      var coe = 20
      coe =
        coe / this.trueWidth > coe / this.trueHeight
          ? coe / this.trueHeight
          : coe / this.trueWidth
      num = num * coe
      num > 0
        ? (scale += Math.abs(num))
        : scale > Math.abs(num)
        ? (scale -= Math.abs(num))
        : scale
      if (!this.checkoutImgAxis(this.x, this.y, scale)) {
        return false
      }
      this.scale = scale
    },
    // 创建截图框
    createCrop(e) {
      e.preventDefault()
      // 移动生成大小
      var nowX = e.clientX ? e.clientX : e.touches ? e.touches[0].clientX : 0
      var nowY = e.clientY ? e.clientY : e.touches ? e.touches[0].clientY : 0
      this.$nextTick(() => {
        // 截图框大小
        var fw = nowX - this.cropX
        var fh = nowY - this.cropY
        if (fw > 0) {
          this.cropW =
            fw + this.cropChangeX > this.w ? this.w - this.cropChangeX : fw
          this.cropOffsertX = this.cropChangeX
        } else {
          this.cropW =
            this.w - this.cropChangeX + Math.abs(fw) > this.w
              ? this.cropChangeX
              : Math.abs(fw)
          this.cropOffsertX =
            this.cropChangeX + fw > 0 ? this.cropChangeX + fw : 0
        }

        if (!this.fixed) {
          if (fh > 0) {
            this.cropH =
              fh + this.cropChangeY > this.h ? this.h - this.cropChangeY : fh
            this.cropOffsertY = this.cropChangeY
          } else {
            this.cropH =
              this.h - this.cropChangeY + Math.abs(fh) > this.h
                ? this.cropChangeY
                : Math.abs(fh)
            this.cropOffsertY =
              this.cropChangeY + fh > 0 ? this.cropChangeY + fh : 0
          }
        } else {
          var fixedHeight =
            (this.cropW / this.fixedNumber[0]) * this.fixedNumber[1]
          if (fixedHeight + this.cropOffsertY > this.h) {
            this.cropH = this.h - this.cropOffsertY
            this.cropW =
              (this.cropH / this.fixedNumber[1]) * this.fixedNumber[0]
            if (fw > 0) {
              this.cropOffsertX = this.cropChangeX
            } else {
              this.cropOffsertX = this.cropChangeX - this.cropW
            }
          } else {
            this.cropH = fixedHeight
          }
          this.cropOffsertY = this.cropOffsertY
        }
      })
    },

    // 改变截图框大小
    changeCropSize(e, w, h, typeW, typeH) {
      e.preventDefault()
      window.addEventListener('mousemove', this.changeCropNow)
      window.addEventListener('mouseup', this.changeCropEnd)
      window.addEventListener('touchmove', this.changeCropNow)
      window.addEventListener('touchend', this.changeCropEnd)
      this.canChangeX = w
      this.canChangeY = h
      this.changeCropTypeX = typeW
      this.changeCropTypeY = typeH
      this.cropX = e.clientX ? e.clientX : e.touches[0].clientX
      this.cropY = e.clientY ? e.clientY : e.touches[0].clientY
      this.cropOldW = this.cropW
      this.cropOldH = this.cropH
      this.cropChangeX = this.cropOffsertX
      this.cropChangeY = this.cropOffsertY
      if (this.fixed) {
        if (this.canChangeX && this.canChangeY) {
          this.canChangeY = 0
        }
      }
    },

    // 正在改变
    changeCropNow(e) {
      e.preventDefault()
      var nowX = e.clientX ? e.clientX : e.touches ? e.touches[0].clientX : 0
      var nowY = e.clientY ? e.clientY : e.touches ? e.touches[0].clientY : 0
      // 容器的宽高
      let wrapperW = this.w
      let wrapperH = this.h

      // 不能超过的坐标轴
      let minX = 0
      let minY = 0

      if (this.centerBox) {
        let axis = this.getImgAxis()
        let imgW = axis.x2
        let imgH = axis.y2
        minX = axis.x1 > 0 ? axis.x1 : 0
        minY = axis.y1 > 0 ? axis.y1 : 0
        if (wrapperW > imgW) {
          wrapperW = imgW
        }

        if (wrapperH > imgH) {
          wrapperH = imgH
        }
      }

      this.$nextTick(() => {
        var fw = nowX - this.cropX
        var fh = nowY - this.cropY
        if (this.canChangeX) {
          if (this.changeCropTypeX === 1) {
            if (this.cropOldW - fw > 0) {
              this.cropW =
                wrapperW - this.cropChangeX - fw <= wrapperW - minX
                  ? this.cropOldW - fw
                  : this.cropOldW + this.cropChangeX - minX
              this.cropOffsertX =
                wrapperW - this.cropChangeX - fw <= wrapperW - minX
                  ? this.cropChangeX + fw
                  : minX
            } else {
              this.cropW =
                Math.abs(fw) + this.cropChangeX <= wrapperW
                  ? Math.abs(fw) - this.cropOldW
                  : wrapperW - this.cropOldW - this.cropChangeX
              this.cropOffsertX = this.cropChangeX + this.cropOldW
            }
          } else if (this.changeCropTypeX === 2) {
            if (this.cropOldW + fw > 0) {
              this.cropW =
                this.cropOldW + fw + this.cropOffsertX <= wrapperW
                  ? this.cropOldW + fw
                  : wrapperW - this.cropOffsertX
              this.cropOffsertX = this.cropChangeX
            } else {
              // 右侧坐标抽 超过左侧
              this.cropW =
                wrapperW - this.cropChangeX + Math.abs(fw + this.cropOldW) <=
                wrapperW - minX
                  ? Math.abs(fw + this.cropOldW)
                  : this.cropChangeX - minX
              this.cropOffsertX =
                wrapperW - this.cropChangeX + Math.abs(fw + this.cropOldW) <=
                wrapperW - minX
                  ? this.cropChangeX - Math.abs(fw + this.cropOldW)
                  : minX
            }
          }
        }

        if (this.canChangeY) {
          if (this.changeCropTypeY === 1) {
            if (this.cropOldH - fh > 0) {
              this.cropH =
                wrapperH - this.cropChangeY - fh <= wrapperH - minY
                  ? this.cropOldH - fh
                  : this.cropOldH + this.cropChangeY - minY
              this.cropOffsertY =
                wrapperH - this.cropChangeY - fh <= wrapperH - minY
                  ? this.cropChangeY + fh
                  : minY
            } else {
              this.cropH =
                Math.abs(fh) + this.cropChangeY <= wrapperH
                  ? Math.abs(fh) - this.cropOldH
                  : wrapperH - this.cropOldH - this.cropChangeY
              this.cropOffsertY = this.cropChangeY + this.cropOldH
            }
          } else if (this.changeCropTypeY === 2) {
            if (this.cropOldH + fh > 0) {
              this.cropH =
                this.cropOldH + fh + this.cropOffsertY <= wrapperH
                  ? this.cropOldH + fh
                  : wrapperH - this.cropOffsertY
              this.cropOffsertY = this.cropChangeY
            } else {
              this.cropH =
                wrapperH - this.cropChangeY + Math.abs(fh + this.cropOldH) <=
                wrapperH - minY
                  ? Math.abs(fh + this.cropOldH)
                  : this.cropChangeY - minY
              this.cropOffsertY =
                wrapperH - this.cropChangeY + Math.abs(fh + this.cropOldH) <=
                wrapperH - minY
                  ? this.cropChangeY - Math.abs(fh + this.cropOldH)
                  : minY
            }
          }
        }

        if (this.canChangeX && this.fixed) {
          var fixedHeight =
            (this.cropW / this.fixedNumber[0]) * this.fixedNumber[1]
          if (fixedHeight + this.cropOffsertY > wrapperH) {
            this.cropH = wrapperH - this.cropOffsertY
            this.cropW =
              (this.cropH / this.fixedNumber[1]) * this.fixedNumber[0]
          } else {
            this.cropH = fixedHeight
          }
        }

        if (this.canChangeY && this.fixed) {
          var fixedWidth =
            (this.cropH / this.fixedNumber[1]) * this.fixedNumber[0]
          if (fixedWidth + this.cropOffsertX > wrapperW) {
            this.cropW = wrapperW - this.cropOffsertX
            this.cropH =
              (this.cropW / this.fixedNumber[0]) * this.fixedNumber[1]
          } else {
            this.cropW = fixedWidth
          }
        }
      })
    },

    // 结束改变
    changeCropEnd(e) {
      // 抛出改变后截图的大小
      this.$emit('changeCropEnd', this.getCropAxis())
      window.removeEventListener('mousemove', this.changeCropNow)
      window.removeEventListener('mouseup', this.changeCropEnd)
      window.removeEventListener('touchmove', this.changeCropNow)
      window.removeEventListener('touchend', this.changeCropEnd)
    },

    // 创建完成
    endCrop() {
      if (this.cropW === 0 && this.cropH === 0) {
        this.cropping = false
      }
      // 截图完成 截图有效范围是10×10
      if (this.cropInfo.width >= 10 && this.cropInfo.height >= 10) {
        this.$emit('cropFinishd', 'end')
      }
      window.removeEventListener('mousemove', this.createCrop)
      window.removeEventListener('mouseup', this.endCrop)
      window.removeEventListener('touchmove', this.createCrop)
      window.removeEventListener('touchend', this.endCrop)
    },
    // 开始截图
    startCrop() {
      this.crop = true
      // console.log('开始截图')
    },
    // 停止截图
    stopCrop() {
      this.crop = false
      // console.log('停止截图')
    },
    // 清除截图
    clearCrop() {
      this.cropping = false
      this.cropW = 0
      this.cropH = 0
      // console.log('清除截图')
    },
    // 截图移动
    cropMove(e) {
      e.preventDefault()
      if (!this.canMoveBox) {
        this.crop = false
        this.startMove(e)
        return false
      }

      if (e.touches && e.touches.length === 2) {
        this.crop = false
        this.startMove(e)
        this.leaveCrop()
        return false
      }
      window.addEventListener('mousemove', this.moveCrop)
      window.addEventListener('mouseup', this.leaveCrop)
      window.addEventListener('touchmove', this.moveCrop)
      window.addEventListener('touchend', this.leaveCrop)
      let x = e.clientX ? e.clientX : e.touches[0].clientX
      let y = e.clientY ? e.clientY : e.touches[0].clientY
      let newX, newY
      newX = x - this.cropOffsertX
      newY = y - this.cropOffsertY
      this.cropX = newX
      this.cropY = newY
      // 触发截图框移动事件
      this.$emit('cropMoving', {
        moving: true,
        axis: this.getCropAxis()
      })
    },

    moveCrop(e, isMove) {
      let nowX = 0
      let nowY = 0
      if (e) {
        e.preventDefault()
        nowX = e.clientX ? e.clientX : e.touches[0].clientX
        nowY = e.clientY ? e.clientY : e.touches[0].clientY
      }
      this.$nextTick(() => {
        let cx, cy
        let fw = nowX - this.cropX
        let fh = nowY - this.cropY
        if (isMove) {
          fw = this.cropOffsertX
          fh = this.cropOffsertY
        }
        // 不能超过外层容器
        if (fw <= 0) {
          cx = 0
        } else if (fw + this.cropW > this.w) {
          cx = this.w - this.cropW
        } else {
          cx = fw
        }

        if (fh <= 0) {
          cy = 0
        } else if (fh + this.cropH > this.h) {
          cy = this.h - this.cropH
        } else {
          cy = fh
        }

        // 不能超过图片
        if (this.centerBox) {
          let axis = this.getImgAxis()
          // 横坐标判断
          if (cx <= axis.x1) {
            cx = axis.x1
          }

          if (cx + this.cropW > axis.x2) {
            cx = axis.x2 - this.cropW
          }

          // 纵坐标纵轴
          if (cy <= axis.y1) {
            cy = axis.y1
          }

          if (cy + this.cropH > axis.y2) {
            cy = axis.y2 - this.cropH
          }
        }

        this.cropOffsertX = cx
        this.cropOffsertY = cy

        // 触发截图框移动事件
        this.$emit('cropMoving', {
          moving: true,
          axis: this.getCropAxis()
        })
      })
    },

    // 算出不同场景下面 图片相对于外层容器的坐标轴
    getImgAxis(x, y, scale) {
      x = x || this.x
      y = y || this.y
      scale = scale || this.scale
      // 如果设置了截图框在图片内, 那么限制截图框不能超过图片的坐标
      // 图片的坐标
      let obj = {
        x1: 0,
        x2: 0,
        y1: 0,
        y2: 0
      }
      let imgW = this.trueWidth * scale
      let imgH = this.trueHeight * scale
      switch (this.rotate) {
        case 0:
          obj.x1 = x + (this.trueWidth * (1 - scale)) / 2
          obj.x2 = obj.x1 + this.trueWidth * scale
          obj.y1 = y + (this.trueHeight * (1 - scale)) / 2
          obj.y2 = obj.y1 + this.trueHeight * scale
          break
        case 1:
        case -1:
        case 3:
        case -3:
          obj.x1 = x + (this.trueWidth * (1 - scale)) / 2 + (imgW - imgH) / 2
          obj.x2 = obj.x1 + this.trueHeight * scale
          obj.y1 = y + (this.trueHeight * (1 - scale)) / 2 + (imgH - imgW) / 2
          obj.y2 = obj.y1 + this.trueWidth * scale
          break
        default:
          obj.x1 = x + (this.trueWidth * (1 - scale)) / 2
          obj.x2 = obj.x1 + this.trueWidth * scale
          obj.y1 = y + (this.trueHeight * (1 - scale)) / 2
          obj.y2 = obj.y1 + this.trueHeight * scale
          break
      }
      return obj
    },

    // 获取截图框的坐标轴以及缩放率
    getCropAxis() {
      let obj = {
        x1: 0,
        x2: 0,
        y1: 0,
        y2: 0,
        //以下宽高偏移量用于自动截图
        cropW: 0,
        cropH: 0,
        cropOffsertX: 0,
        cropOffsertY: 0,
        scale: this.scale
      }
      obj.x1 = this.cropOffsertX
      obj.x2 = obj.x1 + this.cropW
      obj.cropW = this.cropW
      obj.cropOffsertX = this.cropOffsertX
      obj.y1 = this.cropOffsertY
      obj.y2 = obj.y1 + this.cropH
      obj.cropH = this.cropH
      obj.cropOffsertY = this.cropOffsertY
      return obj
    },
    leaveCrop(e) {
      window.removeEventListener('mousemove', this.moveCrop)
      window.removeEventListener('mouseup', this.leaveCrop)
      // window.removeEventListener('touchmove', this.moveCrop)
      // window.removeEventListener('touchend', this.leaveCrop)
      // 触发截图框移动事件
      this.$emit('cropMoving', {
        moving: false,
        axis: this.getCropAxis()
      })
    },

    getCropChecked(cb) {
      let canvas = document.createElement('canvas')
      let img = new Image()
      let rotate = this.rotate
      let trueWidth = this.trueWidth
      let trueHeight = this.trueHeight
      let cropOffsertX = this.cropOffsertX
      let cropOffsertY = this.cropOffsertY
      img.onload = () => {
        if (this.cropW !== 0) {
          let ctx = canvas.getContext('2d')
          let dpr = 1
          if (this.high & !this.full) {
            dpr = window.devicePixelRatio
          }
          if ((this.enlarge !== 1) & !this.full) {
            dpr = Math.abs(Number(this.enlarge))
            console.log(dpr)
          }
          let width = this.cropW * dpr
          let height = this.cropH * dpr
          let imgW = trueWidth * this.scale * dpr
          let imgH = trueHeight * this.scale * dpr
          // 图片x轴偏移
          let dx =
            (this.x - cropOffsertX + (this.trueWidth * (1 - this.scale)) / 2) *
            dpr
          // 图片y轴偏移
          let dy =
            (this.y - cropOffsertY + (this.trueHeight * (1 - this.scale)) / 2) *
            dpr
          // console.log(dx, dy)
          // 保存状态
          setCanvasSize(width, height)
          ctx.save()
          switch (rotate) {
            case 0:
              if (!this.full) {
                ctx.drawImage(img, dx, dy, imgW, imgH)
              } else {
                // 输出原图比例截图
                setCanvasSize(width / this.scale, height / this.scale)
                ctx.drawImage(
                  img,
                  dx / this.scale,
                  dy / this.scale,
                  imgW / this.scale,
                  imgH / this.scale
                )
              }
              break
            case 1:
            case -3:
              if (!this.full) {
                // 换算图片旋转后的坐标弥补
                dx = dx + (imgW - imgH) / 2
                dy = dy + (imgH - imgW) / 2
                ctx.rotate((rotate * 90 * Math.PI) / 180)
                ctx.drawImage(img, dy, -dx - imgH, imgW, imgH)
              } else {
                setCanvasSize(width / this.scale, height / this.scale)
                // 换算图片旋转后的坐标弥补
                dx =
                  dx / this.scale + (imgW / this.scale - imgH / this.scale) / 2
                dy =
                  dy / this.scale + (imgH / this.scale - imgW / this.scale) / 2
                ctx.rotate((rotate * 90 * Math.PI) / 180)
                ctx.drawImage(
                  img,
                  dy,
                  -dx - imgH / this.scale,
                  imgW / this.scale,
                  imgH / this.scale
                )
              }
              break
            case 2:
            case -2:
              if (!this.full) {
                ctx.rotate((rotate * 90 * Math.PI) / 180)
                ctx.drawImage(img, -dx - imgW, -dy - imgH, imgW, imgH)
              } else {
                setCanvasSize(width / this.scale, height / this.scale)
                ctx.rotate((rotate * 90 * Math.PI) / 180)
                dx = dx / this.scale
                dy = dy / this.scale
                ctx.drawImage(
                  img,
                  -dx - imgW / this.scale,
                  -dy - imgH / this.scale,
                  imgW / this.scale,
                  imgH / this.scale
                )
              }
              break
            case 3:
            case -1:
              if (!this.full) {
                // 换算图片旋转后的坐标弥补
                dx = dx + (imgW - imgH) / 2
                dy = dy + (imgH - imgW) / 2
                ctx.rotate((rotate * 90 * Math.PI) / 180)
                ctx.drawImage(img, -dy - imgW, dx, imgW, imgH)
              } else {
                setCanvasSize(width / this.scale, height / this.scale)
                // 换算图片旋转后的坐标弥补
                dx =
                  dx / this.scale + (imgW / this.scale - imgH / this.scale) / 2
                dy =
                  dy / this.scale + (imgH / this.scale - imgW / this.scale) / 2
                ctx.rotate((rotate * 90 * Math.PI) / 180)
                ctx.drawImage(
                  img,
                  -dy - imgW / this.scale,
                  dx,
                  imgW / this.scale,
                  imgH / this.scale
                )
              }
              break
            default:
              if (!this.full) {
                ctx.drawImage(img, dx, dy, imgW, imgH)
              } else {
                // 输出原图比例截图
                setCanvasSize(width / this.scale, height / this.scale)
                ctx.drawImage(
                  img,
                  dx / this.scale,
                  dy / this.scale,
                  imgW / this.scale,
                  imgH / this.scale
                )
              }
          }
          ctx.restore()
        } else {
          let width = trueWidth * this.scale
          let height = trueHeight * this.scale
          let ctx = canvas.getContext('2d')
          ctx.save()
          switch (rotate) {
            case 0:
              setCanvasSize(width, height)
              ctx.drawImage(img, 0, 0, width, height)
              break
            case 1:
            case -3:
              // 旋转90度 或者-270度 宽度和高度对调
              setCanvasSize(height, width)
              ctx.rotate((rotate * 90 * Math.PI) / 180)
              ctx.drawImage(img, 0, -height, width, height)
              break
            case 2:
            case -2:
              setCanvasSize(width, height)
              ctx.rotate((rotate * 90 * Math.PI) / 180)
              ctx.drawImage(img, -width, -height, width, height)
              break
            case 3:
            case -1:
              setCanvasSize(height, width)
              ctx.rotate((rotate * 90 * Math.PI) / 180)
              ctx.drawImage(img, -width, 0, width, height)
              break
            default:
              setCanvasSize(width, height)
              ctx.drawImage(img, 0, 0, width, height)
          }
          ctx.restore()
        }
        cb(canvas)
      }
      // 判断图片是否是base64
      var s = this.img.substr(0, 4)
      if (s !== 'data') {
        img.crossOrigin = 'Anonymous'
      }
      img.src = this.imgs

      function setCanvasSize(width, height) {
        canvas.width = Math.round(width)
        canvas.height = Math.round(height)
      }
    },

    // 获取转换成base64 的图片信息
    getCropData(cb) {
      this.getCropChecked(data => {
        cb(data.toDataURL('image/' + this.outputType, this.outputSize))
      })
    },

    //canvas获取为blob对象
    getCropBlob(cb) {
      this.getCropChecked(data => {
        data.toBlob(
          blob => cb(blob),
          'image/' + this.outputType,
          this.outputSize
        )
      })
    },

    // 自动预览函数
    showPreview() {
      // 优化不要多次触发
      if (this.isCanShow) {
        this.isCanShow = false
        setTimeout(() => {
          this.isCanShow = true
        }, 16)
      } else {
        return false
      }
      let w = this.cropW
      let h = this.cropH
      let scale = this.scale
      var obj = {}
      obj.div = {
        width: `${w}px`,
        height: `${h}px`
      }
      let transformX = (this.x - this.cropOffsertX) / scale
      let transformY = (this.y - this.cropOffsertY) / scale
      let transformZ = 0
      obj.w = w
      obj.h = h
      obj.cropOffsertX = this.cropOffsertX
      obj.cropOffsertY = this.cropOffsertY
      obj.url = this.imgs
      obj.img = {
        width: `${this.trueWidth}px`,
        height: `${this.trueHeight}px`,
        transform: `scale(${scale})translate3d(${transformX}px, ${transformY}px, ${transformZ}px)rotateZ(${this
          .rotate * 90}deg)`
      }
      obj.html = `
      <div class="show-preview" style="width: ${obj.w}px; height: ${
        obj.h
      }px,; overflow: hidden">
        <div style="width: ${w}px; height: ${h}px">
          <img src=${obj.url} style="width: ${this.trueWidth}px; height: ${
        this.trueHeight
      }px; transform:
          scale(${scale})translate3d(${transformX}px, ${transformY}px, ${transformZ}px)rotateZ(${this
        .rotate * 90}deg)">
        </div>
      </div>`
      this.$emit('realTime', obj)
    },
    // reload 图片布局函数
    reload() {
      let img = new Image()
      img.onload = () => {
        // 读取图片的信息原始信息, 解析是否需要旋转
        // 读取图片的旋转信息
        // 得到外层容器的宽度高度
        this.w = parseFloat(window.getComputedStyle(this.$refs.cropper).width)
        this.h = parseFloat(window.getComputedStyle(this.$refs.cropper).height)
        //将容器宽高等于图片宽高
        // this.w = img.width
        // this.h = img.height
        // 存入图片真实高度
        this.trueWidth = img.width
        this.trueHeight = img.height

        // 判断是否需要压缩大图
        if (!this.original) {
          // 判断布局方式 mode
          this.scale = this.checkedMode()
        } else {
          this.scale = 1
        }

        this.$nextTick(() => {
          this.x =
            -(this.trueWidth - this.trueWidth * this.scale) / 2 +
            (this.w - this.trueWidth * this.scale) / 2
          this.y =
            -(this.trueHeight - this.trueHeight * this.scale) / 2 +
            (this.h - this.trueHeight * this.scale) / 2
          this.loading = false
          // // 获取是否开启了自动截图
          if (this.autoCrop) {
            this.goAutoCrop()
          }
          // 图片加载成功的回调
          this.$emit('imgLoad', 'success')
          setTimeout(() => {
            this.showPreview()
          }, 20)
        })
      }
      img.onerror = () => {
        this.$emit('imgLoad', 'error')
      }
      img.src = this.imgs
    },
    // 背景布局的函数
    checkedMode() {
      let scale = 1
      // 通过字符串分割
      let imgW = this.trueWidth
      let imgH = this.trueHeight
      const arr = this.mode.split(' ')
      switch (arr[0]) {
        case 'contain':
          if (this.trueWidth > this.w) {
            // 如果图片宽度大于容器宽度
            scale = this.w / this.trueWidth
          }

          if (this.trueHeight * scale > this.h) {
            scale = this.h / this.trueHeight
          }
          break
        case 'cover':
          // 扩展布局 默认填充满整个容器
          // 图片宽度大于容器
          imgW = this.w
          scale = imgW / this.trueWidth
          imgH = imgH * scale
          // 如果扩展之后高度小于容器的外层高度 继续扩展高度
          if (imgH < this.h) {
            imgH = this.h
            scale = imgH / this.trueHeight
          }
          break
        default:
          try {
            let str = arr[0]
            if (str.search('px') !== -1) {
              str = str.replace('px', '')
              imgW = parseFloat(str)
              scale = imgW / this.trueWidth
            }
            if (str.search('%') !== -1) {
              str = str.replace('%', '')
              imgW = (parseFloat(str) / 100) * this.w
              scale = imgW / this.trueWidth
            }

            if (arr.length === 2 && str === 'auto') {
              let str2 = arr[1]
              if (str2.search('px') !== -1) {
                str2 = str2.replace('px', '')
                imgH = parseFloat(str2)
                scale = imgH / this.trueHeight
              }
              if (str2.search('%') !== -1) {
                str2 = str2.replace('%', '')
                imgH = (parseFloat(str2) / 100) * this.h
                scale = imgH / this.trueHeight
              }
            }
          } catch (error) {
            scale = 1
          }
      }
      return scale
    },
    // 自动截图函数
    goAutoCrop(cw, ch, offX, offY) {
      this.clearCrop()
      this.cropping = true
      let maxWidth = this.w
      let maxHeight = this.h
      if (this.centerBox) {
        let imgW = this.trueWidth * this.scale
        let imgH = this.trueHeight * this.scale
        maxWidth = imgW < maxWidth ? imgW : maxWidth
        maxHeight = imgH < maxHeight ? imgH : maxHeight
      }
      // 截图框默认大小
      // 如果为0 那么计算容器大小 默认为80%
      var w = cw ? cw : parseFloat(this.autoCropWidth)
      var h = ch ? ch : parseFloat(this.autoCropHeight)
      if (w === 0 || h === 0) {
        w = maxWidth * 0.8
        h = maxHeight * 0.8
      }
      w = w > maxWidth ? maxWidth : w
      h = h > maxHeight ? maxHeight : h
      if (this.fixed) {
        h = (w / this.fixedNumber[0]) * this.fixedNumber[1]
      }
      // 如果比例之后 高度大于h
      if (h > this.h) {
        h = this.h
        w = (h / this.fixedNumber[1]) * this.fixedNumber[0]
      }
      this.changeCrop(w, h, offX, offY)
    },
    // 手动改变截图框大小函数
    changeCrop(w, h, offX, offY) {
      let whRate = w / h
      if (Number.isNaN(whRate))
        whRate = this.fixedNumber[0] / this.fixedNumber[1]
      if (this.centerBox) {
        // 修复初始化时候在centerBox=true情况下
        let axis = this.getImgAxis()
        if (w > axis.x2 - axis.x1) {
          // 宽度超标
          w = axis.x2 - axis.x1
          h = w / whRate
        }
        if (h > axis.y2 - axis.y1) {
          // 高度超标
          h = axis.y2 - axis.y1
          w = h * whRate
        }
      }
      // 判断是否大于容器
      this.cropW = w
      this.cropH = h
      // 居中走一走 (修改后,以传入的cropOffsertX、Y为准)
      // this.cropOffsertX = (this.w - w) / 2
      // this.cropOffsertY = (this.h - h) / 2
      offX ? (this.cropOffsertX = offX) : (this.cropOffsertX = (this.w - w) / 2)
      offY ? (this.cropOffsertY = offY) : (this.cropOffsertY = (this.h - h) / 2)
      if (this.centerBox) {
        this.$nextTick(() => {
          this.moveCrop(null, true)
        })
      }
    },
    // 重置函数, 恢复组件置初始状态
    refresh() {
      // console.log('refresh')
      let img = this.img
      this.imgs = ''
      this.scale = 1
      this.crop = false
      this.rotate = 0
      this.w = 0
      this.h = 0
      this.trueWidth = 0
      this.trueHeight = 0
      this.clearCrop()
      this.$nextTick(() => {
        this.checkedImg()
      })
    },

    // 向左边旋转
    rotateLeft() {
      this.rotate = this.rotate <= -3 ? 0 : this.rotate - 1
    },

    // 向右边旋转
    rotateRight() {
      this.rotate = this.rotate >= 3 ? 0 : this.rotate + 1
    },

    // 清除旋转
    rotateClear() {
      this.rotate = 0
    },

    // 图片坐标点校验
    checkoutImgAxis(x, y, scale) {
      x = x || this.x
      y = y || this.y
      scale = scale || this.scale
      let canGo = true
      // 开始校验 如果说缩放之后的坐标在截图框外 则阻止缩放
      if (this.centerBox) {
        let axis = this.getImgAxis(x, y, scale)
        let cropAxis = this.getCropAxis()
        // 左边的横坐标 图片不能超过截图框
        if (axis.x1 >= cropAxis.x1) {
          canGo = false
        }

        // 右边横坐标
        if (axis.x2 <= cropAxis.x2) {
          canGo = false
        }

        // 纵坐标上面
        if (axis.y1 >= cropAxis.y1) {
          canGo = false
        }

        // 纵坐标下面
        if (axis.y2 <= cropAxis.y2) {
          canGo = false
        }
      }
      return canGo
    }
  },
  mounted() {
    this.support =
      'onwheel' in document.createElement('div')
        ? 'wheel'
        : document.onmousewheel !== undefined
        ? 'mousewheel'
        : 'DOMMouseScroll'
    let that = this
    var u = navigator.userAgent
    this.isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
    // 兼容blob
    if (!HTMLCanvasElement.prototype.toBlob) {
      Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
        value: function(callback, type, quality) {
          var binStr = atob(this.toDataURL(type, quality).split(',')[1]),
            len = binStr.length,
            arr = new Uint8Array(len)
          for (var i = 0; i < len; i++) {
            arr[i] = binStr.charCodeAt(i)
          }
          callback(new Blob([arr], { type: that.type || 'image/png' }))
        }
      })
    }
    this.showPreview()
    this.checkedImg()
  },
  destroyed() {
    window.removeEventListener('mousemove', this.moveCrop)
    window.removeEventListener('mouseup', this.leaveCrop)
    window.removeEventListener('touchmove', this.moveCrop)
    window.removeEventListener('touchend', this.leaveCrop)
  }
}
</script>

<style scoped lang="css">
.vue-cropper {
  position: relative;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  direction: ltr;
  touch-action: none;
  text-align: left;
  background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAAA3NCSVQICAjb4U/gAAAABlBMVEXMzMz////TjRV2AAAACXBIWXMAAArrAAAK6wGCiw1aAAAAHHRFWHRTb2Z0d2FyZQBBZG9iZSBGaXJld29ya3MgQ1M26LyyjAAAABFJREFUCJlj+M/AgBVhF/0PAH6/D/HkDxOGAAAAAElFTkSuQmCC');
}

.cropper-box,
.cropper-box-canvas,
.cropper-drag-box,
.cropper-crop-box,
.cropper-face {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  user-select: none;
}

.cropper-box-canvas img {
  position: relative;
  text-align: left;
  user-select: none;
  transform: none;
  max-width: none;
  max-height: none;
}

.cropper-box {
  overflow: hidden;
}

.cropper-move {
  cursor: move;
}

.cropper-crop {
  cursor: crosshair;
}

.cropper-modal {
  background: rgba(0, 0, 0, 0.5);
}

.cropper-crop-box {
  /*border: 2px solid #39f;*/
}

.cropper-view-box {
  display: block;
  overflow: hidden;
  width: 100%;
  height: 100%;
  outline: 1px solid #39f;
  outline-color: rgba(51, 153, 255, 0.75);
  user-select: none;
}

.cropper-view-box img {
  user-select: none;
  text-align: left;
  max-width: none;
  max-height: none;
}

.cropper-face {
  top: 0;
  left: 0;
  background-color: #fff;
  opacity: 0.1;
}

.crop-info {
  position: absolute;
  left: 0px;
  min-width: 65px;
  text-align: center;
  color: white;
  line-height: 20px;
  background-color: rgba(0, 0, 0, 0.8);
  font-size: 12px;
}

.crop-line {
  position: absolute;
  display: block;
  width: 100%;
  height: 100%;
  opacity: 0.1;
}

.line-w {
  top: -3px;
  left: 0;
  height: 5px;
  cursor: n-resize;
}

.line-a {
  top: 0;
  left: -3px;
  width: 5px;
  cursor: w-resize;
}

.line-s {
  bottom: -3px;
  left: 0;
  height: 5px;
  cursor: s-resize;
}

.line-d {
  top: 0;
  right: -3px;
  width: 5px;
  cursor: e-resize;
}

.crop-point {
  position: absolute;
  width: 8px;
  height: 8px;
  opacity: 0.75;
  background-color: #39f;
  border-radius: 100%;
}

.point1 {
  top: -4px;
  left: -4px;
  cursor: nw-resize;
}

.point2 {
  top: -5px;
  left: 50%;
  margin-left: -3px;
  cursor: n-resize;
}

.point3 {
  top: -4px;
  right: -4px;
  cursor: ne-resize;
}

.point4 {
  top: 50%;
  left: -4px;
  margin-top: -3px;
  cursor: w-resize;
}

.point5 {
  top: 50%;
  right: -4px;
  margin-top: -3px;
  cursor: e-resize;
}

.point6 {
  bottom: -5px;
  left: -4px;
  cursor: sw-resize;
}

.point7 {
  bottom: -5px;
  left: 50%;
  margin-left: -3px;
  cursor: s-resize;
}

.point8 {
  bottom: -5px;
  right: -4px;
  cursor: se-resize;
}

@media screen and (max-width: 500px) {
  .crop-point {
    position: absolute;
    width: 20px;
    height: 20px;
    opacity: 0.45;
    background-color: #39f;
    border-radius: 100%;
  }

  .point1 {
    top: -10px;
    left: -10px;
  }

  .point2,
  .point4,
  .point5,
  .point7 {
    display: none;
  }

  .point3 {
    top: -10px;
    right: -10px;
  }

  .point4 {
    top: 0;
    left: 0;
  }

  .point6 {
    bottom: -10px;
    left: -10px;
  }

  .point8 {
    bottom: -10px;
    right: -10px;
  }
}
</style>