10.0.0 • Published 4 years ago

ng2-panzoom v10.0.0

Weekly downloads
511
License
MIT
Repository
github
Last release
4 years ago

ng2-panzoom

An Angular component for panning and zooming an element or elements using the mouse and mousewheel. Provides rudimentary support for touchscreens (read section on mobile support). It was adapted from the angular-pan-zoom library for AngularJS, but it has been heavily modified. Many thanks go out to Martin Vindahl Olsen for having written it, and for his blessing in this undertaking.

It is built using Angular CLI 9.x, so it may or may not work with Angular versions earlier than this. Please excuse the 'ng2' moniker -- I could switch to 'ngx', but I honestly can't be bothered. It is only tested with the corresponding version of Angular.

This library deliberately parts with certain received Angular wisdom of using only Angular-ish methods to accomplish things. We use native event listeners. We apply CSS transforms directly to the DOM. But as this library doesn't fit the traditional Angular model, as its purpose is only to alter a certain part of the DOM using CSS transforms, without adding, moving or changing anything else, it has no impact on an application's state (except if the app consumes modelChanged observables). By using this approach, it is hoped that compatibility and performance will be maximised.

Demo

Click here for a demo of the module. The demo source can be found here.

Features

  • Zoom using mouse wheel, touch surface, double click, or API controls tied to your own UI.
  • Pan using click/touch and drag, or API calls. When releasing the mouse button or touch surface whilst panning, the pan will come to a gradual stop.

Version 10 Changes

Version 10.x is compiled using Angular 10.x. Per the Angular guidance at the time of writing (https://angular.io/guide/creating-libraries), Ivy is not used for the NPM repo build. The following changes have been made:

  • The jQuery dependency has finally been removed!
  • Updated for and compiled with Angular 10.x.
  • New API helper methods centerContent(), centerTopLeft(), centerBottomLeft(), centerTopRight(), centerBottomRight(), centerX(), and centerY()

Version 10 Potentially Breaking Changes

  • Renamed class panElement to pan-element.
  • Renamed class zoomElement to zoom-element.
  • Renamed class panzoomOverlay to pan-zoom-overlay.

Differences From the Original

  • The pan-zoom service has been eliminated.
  • Free zoom - zooming is no longer limited to switching between two distinct zoom levels. Zoom can now be smoothly and freely controlled using the mouse wheel or trackpad.
  • zoomToFit() animation - using the zoomToFit() function now will animate the view to the a desired rectangle.
  • A convenience method resetView() has been provided to animate the view back to its initial settings.
  • The zoomIn() and zoomOut() API functions now zoom to the last zoomed point rather than the centre point, unless no zoom point has been defined yet.
  • New API methods panToPoint(), panDelta(), panDeltaPercent(), and panDeltaAbsolute() have been added for panning the view.
  • Many performance improvements.
  • The widget has not been migrated from the original project, though this probably shouldn't be hard to do. Pull requests are welcome!
  • Touchscreen support works, but it is not great. Work on this will continue.

Dependencies

  • Angular

Mobile Support -- Actively Soliciting PR's

I am actively soliciting pull requests for mobile support. Read on.

The library implements some basic support that may work with some mobile devices, though pinch-to-zoom still needs considerable work. As the application that this library was developed for was never intended for use with mobile devices, there are no plans to implement full mobile support. As long as this remains the case, I respecfully ask for no more issues concerning mobile support, please. I realise that this will limit adoption, but for an enterprising developer out there, I can't imagine that adding mobile support would be nearly as big of a challenge as it was to port the library to Angular from AngularJS!

Installation

npm install ng2-panzoom --save

app.module.ts:

import { Ng2PanZoomModule } from 'ng2-panzoom';

@NgModule({
  imports: [  ...,
              Ng2PanZoomModule
           ],
  ...
})

export class MyAppModule { }

Usage

This library exposes a component called 'pan-zoom', under which you may place any standard Angular template code. Though the events which trigger panning and zooming are run outside of Angular and thus themselves will not trigger change detection, it should not break change detection for any sub-components.

A configuration object is required, which gets passed in using [config]="myConfig".

It also exposes an API which can be used to interact with the pan/zoom view. The API is obtained through the configuration object (more below).

Top Tip

Be sure to place your pan-zoom component underneath an element with a definite height/width, like an absolute-positioned div. You may not see anything if you don't do this.

import { PanZoomConfig, PanZoomAPI, PanZoomModel } from 'ng2-panzoom';

@Component({
  selector: 'my-component'
  template: `

    <div style="position: absolute; top: 100px; bottom: 0; left: 0; right: 0;">

      <pan-zoom [config]="panzoomConfig">

        <div style="position: relative;">

          <img src="/myimage1.jpg">

        </div>

      </pan-zoom>

    </div>
  `
})


export class MyComponent {
  ...
  private panZoomConfig: PanZoomConfig = new PanZoomConfig;
  ...
}

Configuration

You must first create and then pass in a configuration object (of type PanZoomConfig) via the config input property. This configuration object also contains RXJS Observables which can be used to work with the API and also observe changes to the panzoom view.

private panZoomConfig: PanZoomConfig = new PanZoomConfig;

The following attributes are defined:

NameTypeDefaultDescription
apiBehaviorSubject\<PanZoomAPI>Not ApplicableSubscribe to this observable to obtain access to the API for controlling panzoom programattically. See section below on getting at the API.
zoomLevelsnumber5Number of discrete zoom levels, each one representing a scale. The higher the number, the more zoomed in it is.
neutralZoomLevelnumber2The zoom level at which the contents render at 1:1 scale.
scalePerZoomLevelnumber2.0The difference in actual scale between two adjacent zoom levels.
initialZoomLevelnumberneutralZoomLevelThe initially selected zoom level.
initialPanXnumber0The initial pan in the horizontal direction.
initialPanYnumber0The initial pan in the vertical direction.
initialZoomToFitrectanglenullWhen defined, will initially zoom to fit the given rectangle (see API for explanation of zoom to fit). This overrides the initialZoomLevel, initialPanX, and initialPanY values.
zoomToFitZoomLevelFactornumber0.95A number to indicate how closely zoom to fit will work. 1.0 is a perfect fit. Lowering the number will reveal a bit of the surrounding contents.
zoomOnDoubleClickbooleantrueEnable or disable zooming in on double click.
zoomButtonIncrementnumber1.0The number of zoom levels to zoom on double click.
zoomStepDurationnumber0.2Number of seconds to animate between two adjacent zoom levels.
zoomOnMouseWheelbooleantrueEnable or disable zoom in/out on mouse wheel.
invertMouseWheelbooleanfalseInvert the behaviour of the mouse wheel (or two finger trackpad gesture).
freeMouseWheelbooleantrueBy setting this to true, the mouse wheel will freely zoom the view without respect to discreet zoom levels. With false, moving the mouse wheel will zoom the view by zoomButtonIncrement.
freeMouseWheelFactornumber0.08How much to zoom the view with every tick of the wheel, if using freeMouseWheel.
frictionnumber10.0Constant which controls the friction when dragging and then letting go. The higher the number, the more quickly the animation will come to a stop.
haltSpeednumber100.0Constant which controls when the pan animation has slowed down enough to be terminated. The lower the number, the longer it will take to come to a stop.
panOnClickDragbooleantrueEnable or disable pan on clicking and dragging the mouse.
modelChangedBehaviorSubject<PanZoomModel>Not ApplicableAn RXJS observable which can be subscribed to in order to observe changes to the panzoom view. The model will be passed to the callback function.
keepInBoundsbooleanfalseWhen true, it will not be possible to pan the contents off the screen -- it will snap back when trying to do so. It will not be possible to zoom further out than the neutral zoom level. REMEMBER that the initial zoom level must either be less than or equal to the neutral zoom level, or weird things will happen.
keepInBoundsRestoreForcenumber0.5Constant to control how quickly the contents snap back into place after attempting to pan out of bounds.
keepInBoundsDragPullbacknumber0.7Constant to control the perceived force preventing dragging the contents out of bounds.
dragMouseButtonstring'left'Controls which mouse button drags the view. Valid options are left, middle, and right. NOTE: Using middle and right will disable the default 'auxclick' and 'contextmenu' handlers, respectively. ALSO NOTE: Chrome seems to have a bug that doesn't the permit the 'mousemove' event to fire after middle-click drag until it receives a normal left 'click' event. If anyone can shed any light on this, I'd be happy to hear from you. It's such an edge case, though, that I won't be opening a bug report, but feel free to do so if this affects you.
noDragFromElementClassstringnullIf set, this will prevent click-drag on elements who have a parent element containing a specific class name.
acceleratePanbooleantrueControls whether the pan frame will be hardware accelerated.

API

The panzoom library provides an API for interacting with, observing, and controlling it. The following methods and objects are available from the PanZoomAPI:

  • model: PanZoomModel - The current panzoom model - see the PanZoomModel Interface below.

  • config: PanZoomConfig - The current panzooom configuration.

  • changeZoomLevel(newZoomLevel: number, clickPoint: Point) - This method will reset the view to newZoomLevel, with clickPoint as its centre point.

  • zoomIn() - This will zoom the view in to the last zoomed point by one zoom level.

  • zoomOut() - This will zoom the view out from the last zoomed point by one zoom level.

  • zoomToFit(rectangle: Rect, [duration: number]) - Animates the view to focus on a rectangle of the underlying canvas. duration is how long the animation should take (in seconds), and is optional. rectangle is two coordinates on the canvas which the panZoom view is pan/zooming. See the below section on PanZoom Interfaces for its definition.

  • resetView() - A shortcut method to reset the pan and zoom back to the initial view.

  • getViewPosition(modelPosition: Point) - By passing in x,y coordinates of the original, untransformed content canvas, it will return the current pixel position of this point.

  • getModelPosition(viewPosition: Point) - The reverse operation of getViewPosition().

  • panToPoint(point: Point, [duration: number]) - Will animate the view so that the centre point of the view is at the point parameter coordinates, relative to the original, unzoomed content width and height.

  • panDelta(delta: Point, [duration: number]) - Will pan the view left, right, up, or down, based on a number of pixels relative to the original, unzoomed content.

  • panDeltaPercent(deltaPercent: Point, [duration: number]) - Will pan the view up, down, left, or right, based on a percentage of the original, unzoomed content width and height.

  • panDeltaAbsolute(delta: Point, [duration: number]) - Will pan the view left, right, up, or down, based on a number of pixels. This method doesn't adjust for scale. I'm not sure why you'd want this, but it's provided just in case.

  • centerContent([duration: number]) - Will centre the the content vertically and horizontally at the current scale.

  • centerTopLeft([duration: number]) - Will centre the top-left corner of the content at the current scale.

  • centerBottomLeft([duration: number]) - Will centre the bottom-left corner of the content at the current scale.

  • centerTopRight([duration: number]) - Will centre the top-right corner of the content at the current scale.

  • centerBottomRight([duration: number]) - Will centre the bottom-right corner of the content at the current scale.

  • centerX([duration: number]) - Will centre the view on its X axis.

  • centerY([duration: number]) - Will centre the view on its Y axis.

PanZoom API Interfaces:

interface PanZoomModel {
  zoomLevel: number;
  isPanning?: boolean;
  pan: Point; // how far the view has been moved on the x and y axes.  It is not adjusted for scale
}

interface Point {
  x: number;
  y: number;
}

interface Rect {
  x: number; // the x0 (top left) coordinate
  y: number; // the y0 (top left) coordinate
  width: number; // the x1 (bottom right) coordinate
  height: number; // the y1 (bottom right) coordinate
}

Getting at the API

The panzoom API is exposed through an RxJS observable as a property of the PanZoomConfig class, named api, to which you simply subscribe to obtain the API object. The subscription callback method will be passed the API as its only parameter, of type PanZoomAPI. Because it uses a BehaviorSubject, the callback will immediately trigger when subscribed to, assuming panzoom has already been initialised. If panzoom hasn't yet been initialised, the subscription callback will fire as soon as initialisation occurs.

import { PanZoomConfig, PanZoomAPI, PanZoomModel } from 'ng2-panzoom';
import { Subscription } from 'rxjs';

@Component({ ... })

export class MyComponent implements OnInit, OnDestroy {
 
  private panZoomConfig: PanZoomConfig = new PanZoomConfig;
  private panZoomAPI: PanZoomAPI;
  private apiSubscription: Subscription;

  ngOnInit(): void {
    this.apiSubscription = this.panzoomConfig.api.subscribe( (api: PanZoomAPI) => this.panZoomAPI = api );
  }

  ngOnDestroy(): void {
    this.apiSubscription.unsubscribe();  // don't forget to unsubscribe.  you don't want a memory leak!
  }

}

Now that we have our API stored in this.panZoomAPI, we can access it thusly:

this.panZoomAPI.zoomIn();
this.panZoomAPI.zoomOut();

'Events'

The PanZoomConfig class has an RXJS observable (modelChanged) which can be used to monitor the pan/zoom state from another component. The observable emits type PanZoomModel (see above section on API Interfaces). For instance, when the zoom level reaches a certain level, you may want to display a custom control or content on your page. Another use may be to do something when the panzoom centre point is over a certain part of the view.

Example modelChanged Subscription

import { PanZoomConfig, PanZoomAPI, PanZoomModel } from 'ng2-panzoom';

@Component({ ... })

export class MyComponent implements OnInit, OnDestroy {
 
  private panZoomConfig: PanZoomConfig = new PanZoomConfig;
  private modelChangedSubscription: Subscription;

  ngOnInit(): void {
    this.modelChangedSubscription = this.panzoomConfig.modelChanged.subscribe( (model: PanZoomModel) => this.onModelChanged(model) );
  }

  ngOnDestroy(): void {
    this.modelChangedSubscription.unsubscribe();  // don't forget to unsubscribe.  you don't want a memory leak!
  }

  onModelChanged(model: PanZoomModel): void {
    // do something after receiving your model update here
  }

}

Contributing

Pull requests are welcome.

Reference

Martin Vindahl Olsen's original angular-pan-zoom project on GitHub

10.0.0

4 years ago

9.0.1

4 years ago

9.0.0

4 years ago

8.0.0

4 years ago

2.2.2

5 years ago

2.2.1

5 years ago

2.2.0

5 years ago

2.1.1

5 years ago

2.1.0

5 years ago

2.0.0

5 years ago

1.1.0

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.0

6 years ago

0.9.9

6 years ago

0.9.8

6 years ago

0.9.7

6 years ago

0.9.6

6 years ago

0.9.5

6 years ago

0.9.4

6 years ago

0.9.3

6 years ago

0.9.2

6 years ago

0.9.1

6 years ago

0.9.0

6 years ago