[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

title

Body

[close]

/wp-includes/js/imgareaselect/ -> jquery.imgareaselect.js (source)

   1  /*
   2   * imgAreaSelect jQuery plugin
   3   * version 0.9.10-monkey
   4   *
   5   * Copyright (c) 2008-2013 Michal Wojciechowski (odyniec.net)
   6   *
   7   * Dual licensed under the MIT (MIT-LICENSE.txt)
   8   * and GPL (GPL-LICENSE.txt) licenses.
   9   *
  10   * http://odyniec.net/projects/imgareaselect/
  11   *
  12   */
  13  
  14  (function($) {
  15  
  16  /*
  17   * Math functions will be used extensively, so it's convenient to make a few
  18   * shortcuts
  19   */
  20  var abs = Math.abs,
  21      max = Math.max,
  22      min = Math.min,
  23      round = Math.round;
  24  
  25  /**
  26   * Create a new HTML div element
  27   *
  28   * @return A jQuery object representing the new element
  29   */
  30  function div() {
  31      return $('<div/>');
  32  }
  33  
  34  /**
  35   * imgAreaSelect initialization
  36   *
  37   * @param img
  38   *            A HTML image element to attach the plugin to
  39   * @param options
  40   *            An options object
  41   */
  42  $.imgAreaSelect = function (img, options) {
  43      var
  44          /* jQuery object representing the image */
  45          $img = $(img),
  46  
  47          /* Has the image finished loading? */
  48          imgLoaded,
  49  
  50          /* Plugin elements */
  51  
  52          /* Container box */
  53          $box = div(),
  54          /* Selection area */
  55          $area = div(),
  56          /* Border (four divs) */
  57          $border = div().add(div()).add(div()).add(div()),
  58          /* Outer area (four divs) */
  59          $outer = div().add(div()).add(div()).add(div()),
  60          /* Handles (empty by default, initialized in setOptions()) */
  61          $handles = $([]),
  62  
  63          /*
  64           * Additional element to work around a cursor problem in Opera
  65           * (explained later)
  66           */
  67          $areaOpera,
  68  
  69          /* Image position (relative to viewport) */
  70          left, top,
  71  
  72          /* Image offset (as returned by .offset()) */
  73          imgOfs = { left: 0, top: 0 },
  74  
  75          /* Image dimensions (as returned by .width() and .height()) */
  76          imgWidth, imgHeight,
  77  
  78          /*
  79           * jQuery object representing the parent element that the plugin
  80           * elements are appended to
  81           */
  82          $parent,
  83  
  84          /* Parent element offset (as returned by .offset()) */
  85          parOfs = { left: 0, top: 0 },
  86  
  87          /* Base z-index for plugin elements */
  88          zIndex = 0,
  89  
  90          /* Plugin elements position */
  91          position = 'absolute',
  92  
  93          /* X/Y coordinates of the starting point for move/resize operations */
  94          startX, startY,
  95  
  96          /* Horizontal and vertical scaling factors */
  97          scaleX, scaleY,
  98  
  99          /* Current resize mode ("nw", "se", etc.) */
 100          resize,
 101  
 102          /* Selection area constraints */
 103          minWidth, minHeight, maxWidth, maxHeight,
 104  
 105          /* Aspect ratio to maintain (floating point number) */
 106          aspectRatio,
 107  
 108          /* Are the plugin elements currently displayed? */
 109          shown,
 110  
 111          /* Current selection (relative to parent element) */
 112          x1, y1, x2, y2,
 113  
 114          /* Current selection (relative to scaled image) */
 115          selection = { x1: 0, y1: 0, x2: 0, y2: 0, width: 0, height: 0 },
 116  
 117          /* Document element */
 118          docElem = document.documentElement,
 119  
 120          /* User agent */
 121          ua = navigator.userAgent,
 122  
 123          /* Various helper variables used throughout the code */
 124          $p, d, i, o, w, h, adjusted;
 125  
 126      /*
 127       * Translate selection coordinates (relative to scaled image) to viewport
 128       * coordinates (relative to parent element)
 129       */
 130  
 131      /**
 132       * Translate selection X to viewport X
 133       *
 134       * @param x
 135       *            Selection X
 136       * @return Viewport X
 137       */
 138      function viewX(x) {
 139          return x + imgOfs.left - parOfs.left;
 140      }
 141  
 142      /**
 143       * Translate selection Y to viewport Y
 144       *
 145       * @param y
 146       *            Selection Y
 147       * @return Viewport Y
 148       */
 149      function viewY(y) {
 150          return y + imgOfs.top - parOfs.top;
 151      }
 152  
 153      /*
 154       * Translate viewport coordinates to selection coordinates
 155       */
 156  
 157      /**
 158       * Translate viewport X to selection X
 159       *
 160       * @param x
 161       *            Viewport X
 162       * @return Selection X
 163       */
 164      function selX(x) {
 165          return x - imgOfs.left + parOfs.left;
 166      }
 167  
 168      /**
 169       * Translate viewport Y to selection Y
 170       *
 171       * @param y
 172       *            Viewport Y
 173       * @return Selection Y
 174       */
 175      function selY(y) {
 176          return y - imgOfs.top + parOfs.top;
 177      }
 178  
 179      /*
 180       * Translate event coordinates (relative to document) to viewport
 181       * coordinates
 182       */
 183  
 184      /**
 185       * Get event X and translate it to viewport X
 186       *
 187       * @param event
 188       *            The event object
 189       * @return Viewport X
 190       */
 191      function evX(event) {
 192          return max(event.pageX || 0, touchCoords(event).x) - parOfs.left;
 193      }
 194  
 195      /**
 196       * Get event Y and translate it to viewport Y
 197       *
 198       * @param event
 199       *            The event object
 200       * @return Viewport Y
 201       */
 202      function evY(event) {
 203          return max(event.pageY || 0, touchCoords(event).y) - parOfs.top;
 204      }
 205  
 206      /**
 207       * Get X and Y coordinates of a touch event
 208       *
 209       * @param event
 210       *            The event object
 211       * @return Coordinates object
 212       */
 213      function touchCoords(event) {
 214          var oev = event.originalEvent || {};
 215  
 216          if (oev.touches && oev.touches.length)
 217              return { x: oev.touches[0].pageX, y: oev.touches[0].pageY };
 218          else
 219              return { x: 0, y: 0 };
 220      }
 221  
 222      /**
 223       * Get the current selection
 224       *
 225       * @param noScale
 226       *            If set to <code>true</code>, scaling is not applied to the
 227       *            returned selection
 228       * @return Selection object
 229       */
 230      function getSelection(noScale) {
 231          var sx = noScale || scaleX, sy = noScale || scaleY;
 232  
 233          return { x1: round(selection.x1 * sx),
 234              y1: round(selection.y1 * sy),
 235              x2: round(selection.x2 * sx),
 236              y2: round(selection.y2 * sy),
 237              width: round(selection.x2 * sx) - round(selection.x1 * sx),
 238              height: round(selection.y2 * sy) - round(selection.y1 * sy) };
 239      }
 240  
 241      /**
 242       * Set the current selection
 243       *
 244       * @param x1
 245       *            X coordinate of the upper left corner of the selection area
 246       * @param y1
 247       *            Y coordinate of the upper left corner of the selection area
 248       * @param x2
 249       *            X coordinate of the lower right corner of the selection area
 250       * @param y2
 251       *            Y coordinate of the lower right corner of the selection area
 252       * @param noScale
 253       *            If set to <code>true</code>, scaling is not applied to the
 254       *            new selection
 255       */
 256      function setSelection(x1, y1, x2, y2, noScale) {
 257          var sx = noScale || scaleX, sy = noScale || scaleY;
 258  
 259          selection = {
 260              x1: round(x1 / sx || 0),
 261              y1: round(y1 / sy || 0),
 262              x2: round(x2 / sx || 0),
 263              y2: round(y2 / sy || 0)
 264          };
 265  
 266          selection.width = selection.x2 - selection.x1;
 267          selection.height = selection.y2 - selection.y1;
 268      }
 269  
 270      /**
 271       * Recalculate image and parent offsets
 272       */
 273      function adjust() {
 274          /*
 275           * Do not adjust if image has not yet loaded or if width is not a
 276           * positive number. The latter might happen when imgAreaSelect is put
 277           * on a parent element which is then hidden.
 278           */
 279          if (!imgLoaded || !$img.width())
 280              return;
 281  
 282          /*
 283           * Get image offset. The .offset() method returns float values, so they
 284           * need to be rounded.
 285           */
 286          imgOfs = { left: round($img.offset().left), top: round($img.offset().top) };
 287  
 288          /* Get image dimensions */
 289          imgWidth = $img.innerWidth();
 290          imgHeight = $img.innerHeight();
 291  
 292          imgOfs.top += ($img.outerHeight() - imgHeight) >> 1;
 293          imgOfs.left += ($img.outerWidth() - imgWidth) >> 1;
 294  
 295          /* Set minimum and maximum selection area dimensions */
 296          minWidth = round(options.minWidth / scaleX) || 0;
 297          minHeight = round(options.minHeight / scaleY) || 0;
 298          maxWidth = round(min(options.maxWidth / scaleX || 1<<24, imgWidth));
 299          maxHeight = round(min(options.maxHeight / scaleY || 1<<24, imgHeight));
 300  
 301          /*
 302           * Workaround for jQuery 1.3.2 incorrect offset calculation, originally
 303           * observed in Safari 3. Firefox 2 is also affected.
 304           */
 305          if ($().jquery == '1.3.2' && position == 'fixed' &&
 306              !docElem['getBoundingClientRect'])
 307          {
 308              imgOfs.top += max(document.body.scrollTop, docElem.scrollTop);
 309              imgOfs.left += max(document.body.scrollLeft, docElem.scrollLeft);
 310          }
 311  
 312          /* Determine parent element offset */
 313          parOfs = /absolute|relative/.test($parent.css('position')) ?
 314              { left: round($parent.offset().left) - $parent.scrollLeft(),
 315                  top: round($parent.offset().top) - $parent.scrollTop() } :
 316              position == 'fixed' ?
 317                  { left: $(document).scrollLeft(), top: $(document).scrollTop() } :
 318                  { left: 0, top: 0 };
 319  
 320          left = viewX(0);
 321          top = viewY(0);
 322  
 323          /*
 324           * Check if selection area is within image boundaries, adjust if
 325           * necessary
 326           */
 327          if (selection.x2 > imgWidth || selection.y2 > imgHeight)
 328              doResize();
 329      }
 330  
 331      /**
 332       * Update plugin elements
 333       *
 334       * @param resetKeyPress
 335       *            If set to <code>false</code>, this instance's keypress
 336       *            event handler is not activated
 337       */
 338      function update(resetKeyPress) {
 339          /* If plugin elements are hidden, do nothing */
 340          if (!shown) return;
 341  
 342          /*
 343           * Set the position and size of the container box and the selection area
 344           * inside it
 345           */
 346          $box.css({ left: viewX(selection.x1), top: viewY(selection.y1) })
 347              .add($area).width(w = selection.width).height(h = selection.height);
 348  
 349          /*
 350           * Reset the position of selection area, borders, and handles (IE6/IE7
 351           * position them incorrectly if we don't do this)
 352           */
 353          $area.add($border).add($handles).css({ left: 0, top: 0 });
 354  
 355          /* Set border dimensions */
 356          $border
 357              .width(max(w - $border.outerWidth() + $border.innerWidth(), 0))
 358              .height(max(h - $border.outerHeight() + $border.innerHeight(), 0));
 359  
 360          /* Arrange the outer area elements */
 361          $($outer[0]).css({ left: left, top: top,
 362              width: selection.x1, height: imgHeight });
 363          $($outer[1]).css({ left: left + selection.x1, top: top,
 364              width: w, height: selection.y1 });
 365          $($outer[2]).css({ left: left + selection.x2, top: top,
 366              width: imgWidth - selection.x2, height: imgHeight });
 367          $($outer[3]).css({ left: left + selection.x1, top: top + selection.y2,
 368              width: w, height: imgHeight - selection.y2 });
 369  
 370          w -= $handles.outerWidth();
 371          h -= $handles.outerHeight();
 372  
 373          /* Arrange handles */
 374          switch ($handles.length) {
 375          case 8:
 376              $($handles[4]).css({ left: w >> 1 });
 377              $($handles[5]).css({ left: w, top: h >> 1 });
 378              $($handles[6]).css({ left: w >> 1, top: h });
 379              $($handles[7]).css({ top: h >> 1 });
 380          case 4:
 381              $handles.slice(1,3).css({ left: w });
 382              $handles.slice(2,4).css({ top: h });
 383          }
 384  
 385          if (resetKeyPress !== false) {
 386              /*
 387               * Need to reset the document keypress event handler -- unbind the
 388               * current handler
 389               */
 390              if ($.imgAreaSelect.onKeyPress != docKeyPress)
 391                  $(document).unbind($.imgAreaSelect.keyPress,
 392                      $.imgAreaSelect.onKeyPress);
 393  
 394              if (options.keys)
 395                  /*
 396                   * Set the document keypress event handler to this instance's
 397                   * docKeyPress() function
 398                   */
 399                  $(document)[$.imgAreaSelect.keyPress](
 400                      $.imgAreaSelect.onKeyPress = docKeyPress);
 401          }
 402  
 403          /*
 404           * Internet Explorer displays 1px-wide dashed borders incorrectly by
 405           * filling the spaces between dashes with white. Toggling the margin
 406           * property between 0 and "auto" fixes this in IE6 and IE7 (IE8 is still
 407           * broken). This workaround is not perfect, as it requires setTimeout()
 408           * and thus causes the border to flicker a bit, but I haven't found a
 409           * better solution.
 410           *
 411           * Note: This only happens with CSS borders, set with the borderWidth,
 412           * borderOpacity, borderColor1, and borderColor2 options (which are now
 413           * deprecated). Borders created with GIF background images are fine.
 414           */
 415          if (msie && $border.outerWidth() - $border.innerWidth() == 2) {
 416              $border.css('margin', 0);
 417              setTimeout(function () { $border.css('margin', 'auto'); }, 0);
 418          }
 419      }
 420  
 421      /**
 422       * Do the complete update sequence: recalculate offsets, update the
 423       * elements, and set the correct values of x1, y1, x2, and y2.
 424       *
 425       * @param resetKeyPress
 426       *            If set to <code>false</code>, this instance's keypress
 427       *            event handler is not activated
 428       */
 429      function doUpdate(resetKeyPress) {
 430          adjust();
 431          update(resetKeyPress);
 432          x1 = viewX(selection.x1); y1 = viewY(selection.y1);
 433          x2 = viewX(selection.x2); y2 = viewY(selection.y2);
 434      }
 435  
 436      /**
 437       * Hide or fade out an element (or multiple elements)
 438       *
 439       * @param $elem
 440       *            A jQuery object containing the element(s) to hide/fade out
 441       * @param fn
 442       *            Callback function to be called when fadeOut() completes
 443       */
 444      function hide($elem, fn) {
 445          options.fadeSpeed ? $elem.fadeOut(options.fadeSpeed, fn) : $elem.hide();
 446      }
 447  
 448      /**
 449       * Selection area mousemove event handler
 450       *
 451       * @param event
 452       *            The event object
 453       */
 454      function areaMouseMove(event) {
 455          var x = selX(evX(event)) - selection.x1,
 456              y = selY(evY(event)) - selection.y1;
 457  
 458          if (!adjusted) {
 459              adjust();
 460              adjusted = true;
 461  
 462              $box.one('mouseout', function () { adjusted = false; });
 463          }
 464  
 465          /* Clear the resize mode */
 466          resize = '';
 467  
 468          if (options.resizable) {
 469              /*
 470               * Check if the mouse pointer is over the resize margin area and set
 471               * the resize mode accordingly
 472               */
 473              if (y <= options.resizeMargin)
 474                  resize = 'n';
 475              else if (y >= selection.height - options.resizeMargin)
 476                  resize = 's';
 477              if (x <= options.resizeMargin)
 478                  resize += 'w';
 479              else if (x >= selection.width - options.resizeMargin)
 480                  resize += 'e';
 481          }
 482  
 483          $box.css('cursor', resize ? resize + '-resize' :
 484              options.movable ? 'move' : '');
 485          if ($areaOpera)
 486              $areaOpera.toggle();
 487      }
 488  
 489      /**
 490       * Document mouseup event handler
 491       *
 492       * @param event
 493       *            The event object
 494       */
 495      function docMouseUp(event) {
 496          /* Set back the default cursor */
 497          $('body').css('cursor', '');
 498          /*
 499           * If autoHide is enabled, or if the selection has zero width/height,
 500           * hide the selection and the outer area
 501           */
 502          if (options.autoHide || selection.width * selection.height == 0)
 503              hide($box.add($outer), function () { $(this).hide(); });
 504  
 505          $(document).off('mousemove touchmove', selectingMouseMove);
 506          $box.on('mousemove touchmove', areaMouseMove);
 507  
 508          options.onSelectEnd(img, getSelection());
 509      }
 510  
 511      /**
 512       * Selection area mousedown event handler
 513       *
 514       * @param event
 515       *            The event object
 516       * @return false
 517       */
 518      function areaMouseDown(event) {
 519          if (event.type == 'mousedown' && event.which != 1) return false;
 520  
 521          /*
 522           * With mobile browsers, there is no "moving the pointer over" action,
 523           * so we need to simulate one mousemove event happening prior to
 524           * mousedown/touchstart.
 525           */
 526          areaMouseMove(event);
 527  
 528          adjust();
 529  
 530          if (resize) {
 531              /* Resize mode is in effect */
 532              $('body').css('cursor', resize + '-resize');
 533  
 534              x1 = viewX(selection[/w/.test(resize) ? 'x2' : 'x1']);
 535              y1 = viewY(selection[/n/.test(resize) ? 'y2' : 'y1']);
 536  
 537              $(document).on('mousemove touchmove', selectingMouseMove)
 538                  .one('mouseup touchend', docMouseUp);
 539              $box.off('mousemove touchmove', areaMouseMove);
 540          }
 541          else if (options.movable) {
 542              startX = left + selection.x1 - evX(event);
 543              startY = top + selection.y1 - evY(event);
 544  
 545              $box.off('mousemove touchmove', areaMouseMove);
 546  
 547              $(document).on('mousemove touchmove', movingMouseMove)
 548                  .one('mouseup touchend', function () {
 549                      options.onSelectEnd(img, getSelection());
 550  
 551                      $(document).off('mousemove touchmove', movingMouseMove);
 552                      $box.on('mousemove touchmove', areaMouseMove);
 553                  });
 554          }
 555          else
 556              $img.mousedown(event);
 557  
 558          return false;
 559      }
 560  
 561      /**
 562       * Adjust the x2/y2 coordinates to maintain aspect ratio (if defined)
 563       *
 564       * @param xFirst
 565       *            If set to <code>true</code>, calculate x2 first. Otherwise,
 566       *            calculate y2 first.
 567       */
 568      function fixAspectRatio(xFirst) {
 569          if (aspectRatio)
 570              if (xFirst) {
 571                  x2 = max(left, min(left + imgWidth,
 572                      x1 + abs(y2 - y1) * aspectRatio * (x2 > x1 || -1)));
 573                  y2 = round(max(top, min(top + imgHeight,
 574                      y1 + abs(x2 - x1) / aspectRatio * (y2 > y1 || -1))));
 575                  x2 = round(x2);
 576              }
 577              else {
 578                  y2 = max(top, min(top + imgHeight,
 579                      y1 + abs(x2 - x1) / aspectRatio * (y2 > y1 || -1)));
 580                  x2 = round(max(left, min(left + imgWidth,
 581                      x1 + abs(y2 - y1) * aspectRatio * (x2 > x1 || -1))));
 582                  y2 = round(y2);
 583              }
 584      }
 585  
 586      /**
 587       * Resize the selection area respecting the minimum/maximum dimensions and
 588       * aspect ratio
 589       */
 590      function doResize() {
 591          /*
 592           * Make sure the top left corner of the selection area stays within
 593           * image boundaries (it might not if the image source was dynamically
 594           * changed).
 595           */
 596          x1 = min(x1, left + imgWidth);
 597          y1 = min(y1, top + imgHeight);
 598  
 599          if (abs(x2 - x1) < minWidth) {
 600              /* Selection width is smaller than minWidth */
 601              x2 = x1 - minWidth * (x2 < x1 || -1);
 602  
 603              if (x2 < left)
 604                  x1 = left + minWidth;
 605              else if (x2 > left + imgWidth)
 606                  x1 = left + imgWidth - minWidth;
 607          }
 608  
 609          if (abs(y2 - y1) < minHeight) {
 610              /* Selection height is smaller than minHeight */
 611              y2 = y1 - minHeight * (y2 < y1 || -1);
 612  
 613              if (y2 < top)
 614                  y1 = top + minHeight;
 615              else if (y2 > top + imgHeight)
 616                  y1 = top + imgHeight - minHeight;
 617          }
 618  
 619          x2 = max(left, min(x2, left + imgWidth));
 620          y2 = max(top, min(y2, top + imgHeight));
 621  
 622          fixAspectRatio(abs(x2 - x1) < abs(y2 - y1) * aspectRatio);
 623  
 624          if (abs(x2 - x1) > maxWidth) {
 625              /* Selection width is greater than maxWidth */
 626              x2 = x1 - maxWidth * (x2 < x1 || -1);
 627              fixAspectRatio();
 628          }
 629  
 630          if (abs(y2 - y1) > maxHeight) {
 631              /* Selection height is greater than maxHeight */
 632              y2 = y1 - maxHeight * (y2 < y1 || -1);
 633              fixAspectRatio(true);
 634          }
 635  
 636          selection = { x1: selX(min(x1, x2)), x2: selX(max(x1, x2)),
 637              y1: selY(min(y1, y2)), y2: selY(max(y1, y2)),
 638              width: abs(x2 - x1), height: abs(y2 - y1) };
 639  
 640          update();
 641  
 642          options.onSelectChange(img, getSelection());
 643      }
 644  
 645      /**
 646       * Mousemove event handler triggered when the user is selecting an area
 647       *
 648       * @param event
 649       *            The event object
 650       * @return false
 651       */
 652      function selectingMouseMove(event) {
 653          x2 = /w|e|^$/.test(resize) || aspectRatio ? evX(event) : viewX(selection.x2);
 654          y2 = /n|s|^$/.test(resize) || aspectRatio ? evY(event) : viewY(selection.y2);
 655  
 656          doResize();
 657  
 658          return false;
 659      }
 660  
 661      /**
 662       * Move the selection area
 663       *
 664       * @param newX1
 665       *            New viewport X1
 666       * @param newY1
 667       *            New viewport Y1
 668       */
 669      function doMove(newX1, newY1) {
 670          x2 = (x1 = newX1) + selection.width;
 671          y2 = (y1 = newY1) + selection.height;
 672  
 673          $.extend(selection, { x1: selX(x1), y1: selY(y1), x2: selX(x2),
 674              y2: selY(y2) });
 675  
 676          update();
 677  
 678          options.onSelectChange(img, getSelection());
 679      }
 680  
 681      /**
 682       * Mousemove event handler triggered when the selection area is being moved
 683       *
 684       * @param event
 685       *            The event object
 686       * @return false
 687       */
 688      function movingMouseMove(event) {
 689          x1 = max(left, min(startX + evX(event), left + imgWidth - selection.width));
 690          y1 = max(top, min(startY + evY(event), top + imgHeight - selection.height));
 691  
 692          doMove(x1, y1);
 693  
 694          event.preventDefault();
 695          return false;
 696      }
 697  
 698      /**
 699       * Start selection
 700       */
 701      function startSelection() {
 702          $(document).off('mousemove touchmove', startSelection);
 703          adjust();
 704  
 705          x2 = x1;
 706          y2 = y1;
 707          doResize();
 708  
 709          resize = '';
 710  
 711          if (!$outer.is(':visible'))
 712              /* Show the plugin elements */
 713              $box.add($outer).hide().fadeIn(options.fadeSpeed||0);
 714  
 715          shown = true;
 716  
 717          $(document).off('mouseup touchend', cancelSelection)
 718              .on('mousemove touchmove', selectingMouseMove)
 719              .one('mouseup touchend', docMouseUp);
 720          $box.off('mousemove touchmove', areaMouseMove);
 721  
 722          options.onSelectStart(img, getSelection());
 723      }
 724  
 725      /**
 726       * Cancel selection
 727       */
 728      function cancelSelection() {
 729          $(document).off('mousemove touchmove', startSelection)
 730              .off('mouseup touchend', cancelSelection);
 731          hide($box.add($outer));
 732  
 733          setSelection(selX(x1), selY(y1), selX(x1), selY(y1));
 734  
 735          /* If this is an API call, callback functions should not be triggered */
 736          if (!(this instanceof $.imgAreaSelect)) {
 737              options.onSelectChange(img, getSelection());
 738              options.onSelectEnd(img, getSelection());
 739          }
 740      }
 741  
 742      /**
 743       * Image mousedown event handler
 744       *
 745       * @param event
 746       *            The event object
 747       * @return false
 748       */
 749      function imgMouseDown(event) {
 750          /* Ignore the event if animation is in progress */
 751          if (event.which > 1 || $outer.is(':animated')) return false;
 752  
 753          adjust();
 754          startX = x1 = evX(event);
 755          startY = y1 = evY(event);
 756  
 757          /* Selection will start when the mouse is moved */
 758          $(document).on({ 'mousemove touchmove': startSelection,
 759              'mouseup touchend': cancelSelection });
 760  
 761          return false;
 762      }
 763  
 764      /**
 765       * Window resize event handler
 766       */
 767      function windowResize() {
 768          doUpdate(false);
 769      }
 770  
 771      /**
 772       * Image load event handler. This is the final part of the initialization
 773       * process.
 774       */
 775      function imgLoad() {
 776          imgLoaded = true;
 777  
 778          /* Set options */
 779          setOptions(options = $.extend({
 780              classPrefix: 'imgareaselect',
 781              movable: true,
 782              parent: 'body',
 783              resizable: true,
 784              resizeMargin: 10,
 785              onInit: function () {},
 786              onSelectStart: function () {},
 787              onSelectChange: function () {},
 788              onSelectEnd: function () {}
 789          }, options));
 790  
 791          $box.add($outer).css({ visibility: '' });
 792  
 793          if (options.show) {
 794              shown = true;
 795              adjust();
 796              update();
 797              $box.add($outer).hide().fadeIn(options.fadeSpeed||0);
 798          }
 799  
 800          /*
 801           * Call the onInit callback. The setTimeout() call is used to ensure
 802           * that the plugin has been fully initialized and the object instance is
 803           * available (so that it can be obtained in the callback).
 804           */
 805          setTimeout(function () { options.onInit(img, getSelection()); }, 0);
 806      }
 807  
 808      /**
 809       * Document keypress event handler
 810       *
 811       * @param event
 812       *            The event object
 813       * @return false
 814       */
 815      var docKeyPress = function(event) {
 816          var k = options.keys, d, t, key = event.keyCode;
 817  
 818          d = !isNaN(k.alt) && (event.altKey || event.originalEvent.altKey) ? k.alt :
 819              !isNaN(k.ctrl) && event.ctrlKey ? k.ctrl :
 820              !isNaN(k.shift) && event.shiftKey ? k.shift :
 821              !isNaN(k.arrows) ? k.arrows : 10;
 822  
 823          if (k.arrows == 'resize' || (k.shift == 'resize' && event.shiftKey) ||
 824              (k.ctrl == 'resize' && event.ctrlKey) ||
 825              (k.alt == 'resize' && (event.altKey || event.originalEvent.altKey)))
 826          {
 827              /* Resize selection */
 828  
 829              switch (key) {
 830              case 37:
 831                  /* Left */
 832                  d = -d;
 833              case 39:
 834                  /* Right */
 835                  t = max(x1, x2);
 836                  x1 = min(x1, x2);
 837                  x2 = max(t + d, x1);
 838                  fixAspectRatio();
 839                  break;
 840              case 38:
 841                  /* Up */
 842                  d = -d;
 843              case 40:
 844                  /* Down */
 845                  t = max(y1, y2);
 846                  y1 = min(y1, y2);
 847                  y2 = max(t + d, y1);
 848                  fixAspectRatio(true);
 849                  break;
 850              default:
 851                  return;
 852              }
 853  
 854              doResize();
 855          }
 856          else {
 857              /* Move selection */
 858  
 859              x1 = min(x1, x2);
 860              y1 = min(y1, y2);
 861  
 862              switch (key) {
 863              case 37:
 864                  /* Left */
 865                  doMove(max(x1 - d, left), y1);
 866                  break;
 867              case 38:
 868                  /* Up */
 869                  doMove(x1, max(y1 - d, top));
 870                  break;
 871              case 39:
 872                  /* Right */
 873                  doMove(x1 + min(d, imgWidth - selX(x2)), y1);
 874                  break;
 875              case 40:
 876                  /* Down */
 877                  doMove(x1, y1 + min(d, imgHeight - selY(y2)));
 878                  break;
 879              default:
 880                  return;
 881              }
 882          }
 883  
 884          return false;
 885      };
 886  
 887      /**
 888       * Apply style options to plugin element (or multiple elements)
 889       *
 890       * @param $elem
 891       *            A jQuery object representing the element(s) to style
 892       * @param props
 893       *            An object that maps option names to corresponding CSS
 894       *            properties
 895       */
 896      function styleOptions($elem, props) {
 897          for (var option in props)
 898              if (options[option] !== undefined)
 899                  $elem.css(props[option], options[option]);
 900      }
 901  
 902      /**
 903       * Set plugin options
 904       *
 905       * @param newOptions
 906       *            The new options object
 907       */
 908      function setOptions(newOptions) {
 909          if (newOptions.parent)
 910              ($parent = $(newOptions.parent)).append($box.add($outer));
 911  
 912          /* Merge the new options with the existing ones */
 913          $.extend(options, newOptions);
 914  
 915          adjust();
 916  
 917          if (newOptions.handles != null) {
 918              /* Recreate selection area handles */
 919              $handles.remove();
 920              $handles = $([]);
 921  
 922              i = newOptions.handles ? newOptions.handles == 'corners' ? 4 : 8 : 0;
 923  
 924              while (i--)
 925                  $handles = $handles.add(div());
 926  
 927              /* Add a class to handles and set the CSS properties */
 928              $handles.addClass(options.classPrefix + '-handle').css({
 929                  position: 'absolute',
 930                  /*
 931                   * The font-size property needs to be set to zero, otherwise
 932                   * Internet Explorer makes the handles too large
 933                   */
 934                  fontSize: 0,
 935                  zIndex: zIndex + 1 || 1
 936              });
 937  
 938              /*
 939               * If handle width/height has not been set with CSS rules, set the
 940               * default 5px
 941               */
 942              if (!parseInt($handles.css('width')) >= 0)
 943                  $handles.width(5).height(5);
 944  
 945              /*
 946               * If the borderWidth option is in use, add a solid border to
 947               * handles
 948               */
 949              if (o = options.borderWidth)
 950                  $handles.css({ borderWidth: o, borderStyle: 'solid' });
 951  
 952              /* Apply other style options */
 953              styleOptions($handles, { borderColor1: 'border-color',
 954                  borderColor2: 'background-color',
 955                  borderOpacity: 'opacity' });
 956          }
 957  
 958          /* Calculate scale factors */
 959          scaleX = options.imageWidth / imgWidth || 1;
 960          scaleY = options.imageHeight / imgHeight || 1;
 961  
 962          /* Set selection */
 963          if (newOptions.x1 != null) {
 964              setSelection(newOptions.x1, newOptions.y1, newOptions.x2,
 965                  newOptions.y2);
 966              newOptions.show = !newOptions.hide;
 967          }
 968  
 969          if (newOptions.keys)
 970              /* Enable keyboard support */
 971              options.keys = $.extend({ shift: 1, ctrl: 'resize' },
 972                  newOptions.keys);
 973  
 974          /* Add classes to plugin elements */
 975          $outer.addClass(options.classPrefix + '-outer');
 976          $area.addClass(options.classPrefix + '-selection');
 977          for (i = 0; i++ < 4;)
 978              $($border[i-1]).addClass(options.classPrefix + '-border' + i);
 979  
 980          /* Apply style options */
 981          styleOptions($area, { selectionColor: 'background-color',
 982              selectionOpacity: 'opacity' });
 983          styleOptions($border, { borderOpacity: 'opacity',
 984              borderWidth: 'border-width' });
 985          styleOptions($outer, { outerColor: 'background-color',
 986              outerOpacity: 'opacity' });
 987          if (o = options.borderColor1)
 988              $($border[0]).css({ borderStyle: 'solid', borderColor: o });
 989          if (o = options.borderColor2)
 990              $($border[1]).css({ borderStyle: 'dashed', borderColor: o });
 991  
 992          /* Append all the selection area elements to the container box */
 993          $box.append($area.add($border).add($areaOpera)).append($handles);
 994  
 995          if (msie) {
 996              if (o = ($outer.css('filter')||'').match(/opacity=(\d+)/))
 997                  $outer.css('opacity', o[1]/100);
 998              if (o = ($border.css('filter')||'').match(/opacity=(\d+)/))
 999                  $border.css('opacity', o[1]/100);
1000          }
1001  
1002          if (newOptions.hide)
1003              hide($box.add($outer));
1004          else if (newOptions.show && imgLoaded) {
1005              shown = true;
1006              $box.add($outer).fadeIn(options.fadeSpeed||0);
1007              doUpdate();
1008          }
1009  
1010          /* Calculate the aspect ratio factor */
1011          aspectRatio = (d = (options.aspectRatio || '').split(/:/))[0] / d[1];
1012  
1013          $img.add($outer).unbind('mousedown', imgMouseDown);
1014  
1015          if (options.disable || options.enable === false) {
1016              /* Disable the plugin */
1017              $box.off({ 'mousemove touchmove': areaMouseMove,
1018                  'mousedown touchstart': areaMouseDown });
1019              $(window).off('resize', windowResize);
1020          }
1021          else {
1022              if (options.enable || options.disable === false) {
1023                  /* Enable the plugin */
1024                  if (options.resizable || options.movable)
1025                      $box.on({ 'mousemove touchmove': areaMouseMove,
1026                          'mousedown touchstart': areaMouseDown });
1027  
1028                  $(window).resize(windowResize);
1029              }
1030  
1031              if (!options.persistent)
1032                  $img.add($outer).on('mousedown touchstart', imgMouseDown);
1033          }
1034  
1035          options.enable = options.disable = undefined;
1036      }
1037  
1038      /**
1039       * Remove plugin completely
1040       */
1041      this.remove = function () {
1042          /*
1043           * Call setOptions with { disable: true } to unbind the event handlers
1044           */
1045          setOptions({ disable: true });
1046          $box.add($outer).remove();
1047      };
1048  
1049      /*
1050       * Public API
1051       */
1052  
1053      /**
1054       * Get current options
1055       *
1056       * @return An object containing the set of options currently in use
1057       */
1058      this.getOptions = function () { return options; };
1059  
1060      /**
1061       * Set plugin options
1062       *
1063       * @param newOptions
1064       *            The new options object
1065       */
1066      this.setOptions = setOptions;
1067  
1068      /**
1069       * Get the current selection
1070       *
1071       * @param noScale
1072       *            If set to <code>true</code>, scaling is not applied to the
1073       *            returned selection
1074       * @return Selection object
1075       */
1076      this.getSelection = getSelection;
1077  
1078      /**
1079       * Set the current selection
1080       *
1081       * @param x1
1082       *            X coordinate of the upper left corner of the selection area
1083       * @param y1
1084       *            Y coordinate of the upper left corner of the selection area
1085       * @param x2
1086       *            X coordinate of the lower right corner of the selection area
1087       * @param y2
1088       *            Y coordinate of the lower right corner of the selection area
1089       * @param noScale
1090       *            If set to <code>true</code>, scaling is not applied to the
1091       *            new selection
1092       */
1093      this.setSelection = setSelection;
1094  
1095      /**
1096       * Cancel selection
1097       */
1098      this.cancelSelection = cancelSelection;
1099  
1100      /**
1101       * Update plugin elements
1102       *
1103       * @param resetKeyPress
1104       *            If set to <code>false</code>, this instance's keypress
1105       *            event handler is not activated
1106       */
1107      this.update = doUpdate;
1108  
1109      /* Do the dreaded browser detection */
1110      var msie = (/msie ([\w.]+)/i.exec(ua)||[])[1],
1111          opera = /opera/i.test(ua),
1112          safari = /webkit/i.test(ua) && !/chrome/i.test(ua);
1113  
1114      /*
1115       * Traverse the image's parent elements (up to <body>) and find the
1116       * highest z-index
1117       */
1118      $p = $img;
1119  
1120      while ($p.length) {
1121          zIndex = max(zIndex,
1122              !isNaN($p.css('z-index')) ? $p.css('z-index') : zIndex);
1123          /* Also check if any of the ancestor elements has fixed position */
1124          if ($p.css('position') == 'fixed')
1125              position = 'fixed';
1126  
1127          $p = $p.parent(':not(body)');
1128      }
1129  
1130      /*
1131       * If z-index is given as an option, it overrides the one found by the
1132       * above loop
1133       */
1134      zIndex = options.zIndex || zIndex;
1135  
1136      if (msie)
1137          $img.attr('unselectable', 'on');
1138  
1139      /*
1140       * In MSIE and WebKit, we need to use the keydown event instead of keypress
1141       */
1142      $.imgAreaSelect.keyPress = msie || safari ? 'keydown' : 'keypress';
1143  
1144      /*
1145       * There is a bug affecting the CSS cursor property in Opera (observed in
1146       * versions up to 10.00) that prevents the cursor from being updated unless
1147       * the mouse leaves and enters the element again. To trigger the mouseover
1148       * event, we're adding an additional div to $box and we're going to toggle
1149       * it when mouse moves inside the selection area.
1150       */
1151      if (opera)
1152          $areaOpera = div().css({ width: '100%', height: '100%',
1153              position: 'absolute', zIndex: zIndex + 2 || 2 });
1154  
1155      /*
1156       * We initially set visibility to "hidden" as a workaround for a weird
1157       * behaviour observed in Google Chrome 1.0.154.53 (on Windows XP). Normally
1158       * we would just set display to "none", but, for some reason, if we do so
1159       * then Chrome refuses to later display the element with .show() or
1160       * .fadeIn().
1161       */
1162      $box.add($outer).css({ visibility: 'hidden', position: position,
1163          overflow: 'hidden', zIndex: zIndex || '0' });
1164      $box.css({ zIndex: zIndex + 2 || 2 });
1165      $area.add($border).css({ position: 'absolute', fontSize: 0 });
1166  
1167      /*
1168       * If the image has been fully loaded, or if it is not really an image (eg.
1169       * a div), call imgLoad() immediately; otherwise, bind it to be called once
1170       * on image load event.
1171       */
1172      img.complete || img.readyState == 'complete' || !$img.is('img') ?
1173          imgLoad() : $img.one('load', imgLoad);
1174  
1175      /*
1176       * MSIE 9.0 doesn't always fire the image load event -- resetting the src
1177       * attribute seems to trigger it. The check is for version 7 and above to
1178       * accommodate for MSIE 9 running in compatibility mode.
1179       */
1180      if (!imgLoaded && msie && msie >= 7)
1181          img.src = img.src;
1182  };
1183  
1184  /**
1185   * Invoke imgAreaSelect on a jQuery object containing the image(s)
1186   *
1187   * @param options
1188   *            Options object
1189   * @return The jQuery object or a reference to imgAreaSelect instance (if the
1190   *         <code>instance</code> option was specified)
1191   */
1192  $.fn.imgAreaSelect = function (options) {
1193      options = options || {};
1194  
1195      this.each(function () {
1196          /* Is there already an imgAreaSelect instance bound to this element? */
1197          if ($(this).data('imgAreaSelect')) {
1198              /* Yes there is -- is it supposed to be removed? */
1199              if (options.remove) {
1200                  /* Remove the plugin */
1201                  $(this).data('imgAreaSelect').remove();
1202                  $(this).removeData('imgAreaSelect');
1203              }
1204              else
1205                  /* Reset options */
1206                  $(this).data('imgAreaSelect').setOptions(options);
1207          }
1208          else if (!options.remove) {
1209              /* No exising instance -- create a new one */
1210  
1211              /*
1212               * If neither the "enable" nor the "disable" option is present, add
1213               * "enable" as the default
1214               */
1215              if (options.enable === undefined && options.disable === undefined)
1216                  options.enable = true;
1217  
1218              $(this).data('imgAreaSelect', new $.imgAreaSelect(this, options));
1219          }
1220      });
1221  
1222      if (options.instance)
1223          /*
1224           * Return the imgAreaSelect instance bound to the first element in the
1225           * set
1226           */
1227          return $(this).data('imgAreaSelect');
1228  
1229      return this;
1230  };
1231  
1232  })(jQuery);


Generated: Fri Oct 25 08:20:01 2019 Cross-referenced by PHPXref 0.7